虚拟摇杆的修改

    上次的代码运行时会有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[1]    fingerId=2        →      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     }

这下怎么试都没问题了。

原文地址:https://www.cnblogs.com/charsoul/p/8711028.html