c# - 如何正确使用 CharacterController.Move() 来移动角色

标签 c# unity3d vector

我创建了一个基本的第一人称 Controller ,但我的问题是当我向前和向侧面移动时我移动得更快。

我如何在 1 Vector3 中添加 moveDirectionForwardmoveDirectionSide 以便能够使用 CharacterController.Move() 而不是 CharacterController .SimpleMove()?

void MovePlayer() {

    // Get Horizontal and Vertical Input
    float horizontalInput = Input.GetAxis ("Horizontal");
    float verticalInput = Input.GetAxis ("Vertical");

    // Calculate the Direction to Move based on the tranform of the Player
    Vector3 moveDirectionForward = transform.forward * verticalInput * walkSpeed * Time.deltaTime;
    Vector3 moveDirectionSide = transform.right * horizontalInput * walkSpeed * Time.deltaTime;

    // Apply Movement to Player
    myCharacterController.SimpleMove (moveDirectionForward + moveDirectionSide);

最佳答案

解决方案是对运动方向使用归一化向量。

// Get Horizontal and Vertical Input
float horizontalInput = Input.GetAxis ("Horizontal");
float verticalInput = Input.GetAxis ("Vertical");

// Calculate the Direction to Move based on the tranform of the Player
Vector3 moveDirectionForward = transform.forward * verticalInput;
Vector3 moveDirectionSide = transform.right * horizontalInput;

//find the direction
Vector3 direction = (moveDirectionForward + moveDirectionSide).normalized;
//find the distance
Vector3 distance = direction * walkSpeed * Time.deltaTime;

// Apply Movement to Player
myCharacterController.Move (distance);

性能说明:

vector.normalized is obtained from vector/vector.magnitude and vector.magnitude is obtained from sqrt(vector.sqrMagnitude) which is heavy to process. To reduce the processing weight you can use vector/vector.sqrMagnitude instead of vector.normalized but be ware the result is not exactly the same, but still is in the same direction.


now i just need to apply gravity

用重力乘以 Time.deltaTime 减去 moveDirection.y。 您还可以使用 Vector3TransformDirection 来简化和减少 MovePlayer 函数中的代码。

public float walkSpeed = 10.0f;
private Vector3 moveDirection = Vector3.zero;
public float gravity = 20.0F;
CharacterController myCharacterController = null;

void Start()
{
    myCharacterController = GetComponent<CharacterController>();
}

void MovePlayer()
{
    moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
    moveDirection = transform.TransformDirection(moveDirection);
    moveDirection *= walkSpeed;

    moveDirection.y -= gravity * Time.deltaTime;
    myCharacterController.Move(moveDirection * Time.deltaTime);
}

关于c# - 如何正确使用 CharacterController.Move() 来移动角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50493987/

相关文章:

c++ - 模型观察矩阵 - C++、OpenGL

excel - 在 Excel 中创建未知大小的向量

c# - GameObject 属性值不会在游戏重启时重置

c# - 使用 MongoDb 和 C# 的模式依赖类到无模式文档

c# - 读取包含多个具有相同属性名称的标签的 xml 文件,并根据用户的输入替换值

c# - 结构是 'pass-by-value' 吗?

c# - 下载图像并将其保存到 Application.persistentDataPath 会挂起应用程序

c# - 为Unity构建C++插件

C++:传递从 vector 获取的数组指针时的EXC_BAD_ACCESS

c# - 如何在给定点停止线程?