2014-03-04 146 views
2

我在創建遊戲的滑動控件時遇到了一些麻煩。我試圖重新創建Subway Surfers遊戲的控件,在Touch.Moved階段中檢測到輕掃,而不是Touch.End階段。現在它大部分時間都在運行,但偶爾會發生(通常情況下)垂直滑動將被處理爲水平滑動。 我已經提出了下面的代碼,預先感謝任何幫助。Unity滑動功能問題

 int swipeIndex = -1; //index of first detected swipe to prevent multiple swipes 
     Vector2 startPos = Vector.zero; //starting position of touch 
     //minSwipeDist is the distance in inches the player must swipe for a correct swipe 
     for (int i = 0; i < Input.touchCount; i++) { 
      Touch touch = Input.touches[i]; 
      switch (touch.phase) { 
       case TouchPhase.Began: 
        if (swipeIndex == -1) { 
         swipeIndex = i; 
         startPos = touch.position; 
        } 
        break; 
       case TouchPhase.Moved: 
        if(i != swipeIndex) 
         break; 
        Vector2 direction = touch.position - startPos; 
        //vertical swipe 
        if (Mathf.Abs(direction.x) < Mathf.Abs(direction.y)) { 
         //swipe up 
         if ((touch.position.y - startPos.y) > minSwipeDist) { 
          //Process Up swipe 
          swipeIndex = -1; 
         } 
         //swipe down 
         else if ((touch.position.y - startPos.y) < -minSwipeDist) { 
          //Process down swipe 
          swipeIndex = -1; 
         } 
        } 
        //horizontal swipe 
        else { 
         //swipe left 
         if ((touch.position.x - startPos.x) < -minSwipeDist) { 
          //process left swipe 
          swipeIndex = -1; 
         } 
         //swipe right 
         else if ((touch.position.x - startPos.x) > minSwipeDist) { 
          //process right swipe 
          swipeIndex = -1; 
         } 
        } 
        break; 
      } 
     } 

回答

1

我認爲你應該將你的代碼從TouchPhase.Moved移動到TouchPhase.Ended。 基本上,當TouchPhase.Began得到觸摸點時,然後在TouchPhase.Moved中繼續更新第二個點,然後在TouchPhase.Ended中處理這兩個點。