2015-01-26 58 views
0

基本上我想要做的是创建一些代码,当触摸在屏幕上滑动时会注册,所以我可以通过触摸控件移动我的角色。用于检测滑动方向的逻辑

我写的东西有时似乎有效,当它发生时,会使角色多次移动。

这里是我的代码:

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"); 

    } 

任何意见将是很有益的

+0

up case ...'y> x && y> -x'?换句话说,你在这里测试什么? – spender 2015-01-26 20:14:03

+0

好吧,这是从我搞乱,因为我变得恼火,但改变它||而不是&&似乎并没有做任何事情 – Zoomz09 2015-01-26 20:17:54

回答

0

一旦你做出了决定,你不需要跑了测试,所以这将是一个理想时间使用else ifelse

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 
    } 
} 
+0

好的谢谢,看起来比我的好多了。这听起来很愚蠢,但Math.Abs​​做什么?它只是使它积极? – Zoomz09 2015-01-26 20:35:16

+0

@ Zoomz09是的,它消除了负数的负数,所以我们正在测试哪一个维数有更多“大小”,而不管它是正数还是负数。 – spender 2015-01-26 20:36:22

+1

这将很方便知道,因为它使这样的事情变得更容易。无论如何感谢您的帮助 – Zoomz09 2015-01-26 20:39:39

0

我写了this简单的教程这基本上是7行代码,像一个魅力。简单而简单。 你只需要在Unity事件系统中使用te build,而不是编写长而无用的代码。 无需使用更新或固定更新。