虛擬搖桿的修改
上次的代碼運行時會有bug:報錯 ArgumentException: Index out of bounds. 即Input.GetTouch()函數進行了越界訪問。於是上網看了看,發現Touch的機制是這樣的:
在四手指同觸摸時,如果撤掉第二根手指,再按下去,會發生:
touch[0] fingerId=0 touch[0] fingerId=0 touch[0] fingerId=0
touch[1] fingerId=1 →
touch[2] fingerId=2 touch[2] fingerId=3 touch[2] fingerId=2
touch[3] fingerId=3 touch[3] fingerId=3
因此不能用fingerID來GetTouch。
我先想的是,在按下時用一個int變量記錄當時的Touches.Length,然後在GetTouch時判斷一個3目運算符,像這樣:
1 Input.GetTouch(eventData.pointerId- 2 (_oldTouchCount > Input.touches.Length ? _oldTouchCount - Input.touches.Length : 0))
但是又想到,如果 0 1 2 3 4 五根手指 ,去掉1 3後,這樣算的話2就不對了,最終還是采用了一個不怎麽雅觀,但是比較穩的辦法:
1 //通過fingerId獲取其當前index 2 private int GetTouchIndex(int fingerID) 3 { 4 for (int i = 0;i < Input.touches.Length; i++) 5 { 6 if (Input.GetTouch(i).fingerId == fingerID) 7 return i; 8 } 9 return -1; 10 }
這下怎麽試都沒問題了。
虛擬搖桿的修改