Unity3D中如何平滑跳转

Sab*_*ber 2 unity-game-engine

我给Player添加了一个CharacterController。但是当我测试跳跃功能时,我发现Player会立即向上移动。

    if (Player.isGrounded) 
    {
        if (jump) 
        {
            Move.y = JumpSpeed;
            jump = false;
            Player.Move (Move * Time.deltaTime);
        }
    }
    Move += Physics.gravity * Time.deltaTime * 4f;
    Player.Move (Move * Time.fixedDeltaTime);`
Run Code Online (Sandbox Code Playgroud)

Uma*_*r M 5

  1. Player.Move()您在一帧中调用了两次。这可能是一个问题。
  2. 您正在向矢量添加重力Move,这意味着当您调用此代码时它总是向上。
  3. 像这样命名变量Move并不是一个好的约定。它在阅读时会造成混乱,因为已经有一个同名的方法。将其更改为moveDirection.

这是示例代码:

public class ExampleClass : MonoBehaviour {
    public float speed = 6.0F;
    public float jumpSpeed = 8.0F;
    public float gravity = 20.0F;
    private Vector3 moveDirection = Vector3.zero;
    CharacterController controller;
    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update() {
        if (controller.isGrounded) {
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
            moveDirection = transform.TransformDirection(moveDirection);
            moveDirection *= speed;
            if (Input.GetButton("Jump"))
                moveDirection.y = jumpSpeed;

        }
        moveDirection.y -= gravity * Time.deltaTime;
        controller.Move(moveDirection * Time.deltaTime);
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。