C# 检测滑动方向的逻辑
基本上,我想做的是创建一些代码,当触摸在屏幕上滑动时,这些代码将被注册,这样我就可以通过触摸控制来移动我的角色 我所写的东西似乎只是偶尔起作用,当它起作用时,它会使角色多次移动 这是我的密码:C# 检测滑动方向的逻辑,c#,unity3d,C#,Unity3d,基本上,我想做的是创建一些代码,当触摸在屏幕上滑动时,这些代码将被注册,这样我就可以通过触摸控制来移动我的角色 我所写的东西似乎只是偶尔起作用,当它起作用时,它会使角色多次移动 这是我的密码: if (Input.touches [0].phase == TouchPhase.Ended) { Debug.Log (Input.touches [0].deltaPosition); if (Input.touches[0].deltaPosition.y >
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 if and 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
}
}
我写了一个简单的教程,基本上有7行代码,工作起来很有魅力。简单明了。
您只需使用te内置Unity事件系统来编写冗长而无用的代码。
无需使用更新或固定更新。up案例。。。y> x&&y>-x?换句话说,你在这里测试什么?好吧,这是我胡闹的原因,因为我很恼火,但是把它改成| |,而不是&&似乎没什么作用。谢谢,看起来比我的好多了。这听起来可能很愚蠢,但是数学Abs做什么呢?是的,它去掉了负数的负数,所以我们正在测试哪个维度的大小更大,而不管它是正数还是负数。这很方便知道,因为它使类似的事情变得更容易。不管怎样,谢谢你的帮助
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
}
}