如何让玩家只朝一个方向移动(Unity)

时间:2017-12-22 09:55:04

标签: unity3d animation physics

我正在尝试在Unity中创建一个游戏,其中玩家只能朝着它面向的方向移动,但是下面的代码允许玩家在所有4个方向上移动。 (这是针对3D项目的)

任何帮助将不胜感激!谢谢!

public class PlayerController : MonoBehaviour {

    public float speed;

    private Rigidbody rb;

    void Start() {
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate() {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

        rb.AddForce(movement * speed);
    }
}

2 个答案:

答案 0 :(得分:0)

所以我没有得到您想要的东西:首先,您说您希望它只向前移动,然后您唯一要做的就是当他按下键时获得,而在未被按下时向前移动。

如果您想说它一次只能向一个方向移动,那么您将必须输入相同的代码,但要进行一些更改: 首先,要使其向前移动,必须先使变换向前,否则,如果旋转它,它将沿相同的方向移动(您不希望那样,不是吗?)。

Vector3 moveDirection = (transform.forward * Input.GetAxis("Vertical") + transform.right * Input.GetAxis("Horizontal")).normalized;
moveDirection.y = 0;
rb.velocity = moveDirection;

然后,要使其一次只能向一个方向移动,必须将最大轴号放在优先位置,如果相等,则应考虑是否要向前或向右移动(轴值) )。

答案 1 :(得分:-1)

根据您发布的代码,我不确定您在哪里存储播放器的面向方向。但是,我认为它存储为Quaternion。如果你有一个名为playerRotation的玩家轮换四元数,那么你可以这样做(警告 - 未经测试):

Vector3 input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
Vector3 normal =  playerRotation * Vector3.forward;
Vector3 movement = Vector3.Dot(normal, input) * input;

如果游戏是第一人称,那么您可以使用快捷方式,只使用Camera.current.transform.forward代替normal向量。

这会将输入方向投射到法线上,让玩家面向方向,这样你的移动力就只能朝着那个方向。