2015-01-26 59 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,而不是編寫長而無用的代碼。 無需使用更新或固定更新。