检测滑动方向的逻辑

Logic for detecting swipe direction

基本上我想做的是创建一些代码,当触摸在屏幕上滑动时会注册,这样我就可以通过触摸控制移动我的角色。

我写的东西似乎有时会起作用,当它起作用时会使角色移动多次。

这是我的代码:

if (Input.touches [0].phase == TouchPhase.Ended) {

        Debug.Log (Input.touches [0].deltaPosition);
        if (Input.touches[0].deltaPosition.y > Input.touches[0].deltaPosition.x || Input.touches[0].deltaPosition.y > (-Input.touches[0].deltaPosition.x))
            movePlayer ("Up");

        if ((-Input.touches[0].deltaPosition.y) > Input.touches[0].deltaPosition.x || (-Input.touches[0].deltaPosition.y) > (-Input.touches[0].deltaPosition.x))
            movePlayer ("Down");

        if ((-Input.touches[0].deltaPosition.x) > Input.touches[0].deltaPosition.y || (-Input.touches[0].deltaPosition.x) > (-Input.touches[0].deltaPosition.y))
            movePlayer ("Left");

        if (Input.touches[0].deltaPosition.x > Input.touches[0].deltaPosition.y || Input.touches[0].deltaPosition.x > (-Input.touches[0].deltaPosition.y))
            movePlayer ("Right");

    }

任何建议都会很有帮助

一旦做出决定,就不需要再进行 运行 测试,因此这是使用 else ifelse[=14 的理想时机=]

if()
{
}
else if()
{
}
else
{
}

确保只有一个案例可以执行。

但是...我认为您的测试存在缺陷。下面的不是更合适吗?

var dp = Input.touches[0].deltaPosition;
if(Math.Abs(dp.x) > Math.Abs(dp.y))
{
    //gesture had more horizonal movement
    if(dp.x < 0)
    {
        //left
    }
    else
    {
        //right
    }
}
else
{
    //gesture had more vertical movement
    if(dp.y < 0)
    {
        //up
    }
    else
    {
        //down
    }
}

我写了 this 简单的教程,基本上只有 7 行代码,而且效果很好。简单易行。 您只需要在 Unity 事件系统中使用 te 构建,而不是编写冗长且无用的代码。 无需使用更新或固定更新。