如何正确使用 CharacterController.Move() 移动角色

Ger*_*rte 2 c# vector unity-game-engine

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

我如何在 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);
Run Code Online (Sandbox Code Playgroud)

Biz*_*han 6

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

// 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);
Run Code Online (Sandbox Code Playgroud)

性能说明:

vector.normalized是从中获得的,vector/vector.magnitude 并且 vector.magnitude是从中获得的sqrt(vector.sqrMagnitude),处理起来很繁重。为了减少处理重量,您可以使用 vector/vector.sqrMagnitude代替vector.normalized但要注意结果并不完全相同,但仍处于同一方向。


现在我只需要施加重力

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

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);
}
Run Code Online (Sandbox Code Playgroud)