我如何使用 Rigidbody.MovePosition 和 Input.GetAxis 作为我的方向

问题描述

void Update()
    {
        MovementAxes = new Vector2(Input.GetAxis("Horizontal"),Input.GetAxis("Vertical"));
    }

    void FixedUpdate()
    {
        HandleMovement(MovementAxes,60f);
    }



    void HandleMovement(Vector2 direction,float MovementAmount)
    {
        if (Input.GetKey("w") || Input.GetKey("s"))
        {
            if (Input.GetKey("w") && GroundCheck())
            {
                GetComponent<Rigidbody2D>().MovePosition((Vector2)transform.position + (direction * MovementAmount * Time.fixedDeltaTime));
            }
            else if (Input.GetKey("s") && !GroundCheck())
            {
                GetComponent<Rigidbody2D>().MovePosition((Vector2)transform.position + (direction * MovementAmount * Time.fixedDeltaTime));
            }
        }
}

我有上面的代码,它使用 Input.GetAxis 作为移动动态刚体的两个 direction 方法MovePosition 参数。

当按下“s”键时,物体按预期下降,但当按下“w”键时,物体抖动,略微上下移动,但期间不一致。当按下“w”键时,我打印出了 distance,Input.GetAxis("Vertical") 的值是负值和正值。

如何使用 MovePosition 恒定移动游戏对象。我宁愿使用 MovePosition 而不是其他 Rigidbody 方法,因为据说它可以“在帧之间创建平滑过渡。”(统一)

解决方法

根据您的问题,我建议对您的 AddForce 使用 Rigidbody2D。 这是一个示例脚本,在 Unity 中包含一个非常简单的 2D Movement

public class PlayerController: MonoBehaviour {

  public float speed;

  private Rigidbody2D _rigidBody2d;

  private void Start() {
    // Cache the value,don't call GetComponent<Rigidbody2D>() in FixedUpdate
    _rigidBody2d = GetComponent<Rigidbody2D> ();
  }

  private void FixedUpdate() {
    // Store horizontal and vertical movement
    var moveHorizontal = Input.GetAxis("Horizontal");
    var moveVertical = Input.GetAxis("Vertical");
    // Create the actual movement
    var movement = new Vector2(moveHorizontal,moveVertical);

    // apply it to your rigidbody by using AddForce
    _rigidBody2d.AddForce(movement * speed);
  }
}