C# 在Unity 5 2D中禁用对角线移动?(使用C)

C# 在Unity 5 2D中禁用对角线移动?(使用C),c#,unity3d,C#,Unity3d,或者更确切地说,我应该说,有效地阻止了对角线运动 关于这一点,网上有很多Q/A,但我一直遇到相同的问题:例如,当水平向左移动时,我可以覆盖当前方向,并通过向上推开始垂直移动,这就是我想要的。但反过来它就不起作用了!垂直移动不能替代水平移动 void Update () { float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); ManageMo

或者更确切地说,我应该说,有效地阻止了对角线运动

关于这一点,网上有很多Q/A,但我一直遇到相同的问题:例如,当水平向左移动时,我可以覆盖当前方向,并通过向上推开始垂直移动,这就是我想要的。但反过来它就不起作用了!垂直移动不能替代水平移动

void Update () {

         float h = Input.GetAxis("Horizontal");
         float v = Input.GetAxis("Vertical");
          ManageMovement(h, v); 
}    

void ManageMovement(float horizontal,float vertical) {

        if (vertical != 0f) {
                horizontal = 0f;
                Vector3 movement = new Vector3 (horizontal, vertical, 0);
                GetComponent<Rigidbody2D> ().velocity = movement * speed;
                return;
            } 

        if (horizontal != 0f) {
            vertical = 0f;
            Vector3 movement = new Vector3 (horizontal, vertical, 0);
            GetComponent<Rigidbody2D> ().velocity = movement * speed;
            return;

        } else {
            Vector3 noMovement = new Vector3 (0, 0, 0);
            GetComponent<Rigidbody2D> ().velocity = noMovement;
        }
    }
如果我颠倒这些If语句的顺序,它就颠倒了问题。所以,这是一个线索。但我不是一个伟大的侦探。我想得到一些帮助

使用输入。而不是GetAxis

GetAxis以-1到1的比例返回浮点值。它返回到0的速度取决于轴设置。如果将“重力”设置为一个非常高的数字,它将更快地返回到0。如果您将灵敏度设置为非常高的数字,它将更快地变为-1或1

因此,根据这些设置,您的函数ManageMovement将被多次调用,并逐渐更改水平和垂直的值

随着时间的推移,输入可能如下所示:

Update #1: ManageMovement(0.2, 1.0)
Update #2: ManageMovement(0.3, 0.9)
...
Update #N: ManageMovement(1.0, 0.0)
因此,当您检查是否垂直时!=0,它将一直保持非零,直到它实际达到0,然后对于之前的所有更新,将水平设置为0


GetAxisRaw不会以这种方式平滑。

尝试将else语句添加到ManageMotation方法:

void ManageMovement(float horizontal,float vertical) {

    if (vertical != 0f) {
            horizontal = 0f;
            Vector3 movement = new Vector3 (horizontal, vertical, 0);
            GetComponent<Rigidbody2D> ().velocity = movement * speed;
            return;
        } 

    else if (horizontal != 0f) {
        vertical = 0f;
        Vector3 movement = new Vector3 (horizontal, vertical, 0);
        GetComponent<Rigidbody2D> ().velocity = movement * speed;
        return;

    } else {
        Vector3 noMovement = new Vector3 (0, 0, 0);
        GetComponent<Rigidbody2D> ().velocity = noMovement;
    }
}

哦,我的上帝!对就是这样。我不敢相信这有多简单,而且解释得很好。非常感谢,太好了。很高兴我能帮忙!如果答案解决了你的问题,请接受。哦!看来我说得有点太早了!这个动作感觉不错,但我还是不能从水平移动到垂直移动/您可以尝试使用类似if vertical>horizontal{…}else if horizontal>vertical{…}else{…}的构造。通常,您不希望将浮点值与零进行比较。对不起,您当然需要对这些值进行算术运算。类似于:if Math.Absvertical>Math.Abshorizontal{…}else ifMath.Abshorizontal>Math.Absvertical{…}else{…}。你好,morlord,我在方法中添加了else,它似乎没有改变任何东西。。垂直运动仍然占主导地位。