在进行一些搜索后(谷歌搜索“unity mobile detect tap”),我发现这是最顶部的搜索结果。@Mothil的回答让我们非常接近解决方案,OP的回答解决了问题。但是,OP的答案没有考虑多次点击。此外,跟踪已启动触摸、已结束触摸和已移动触摸(例如int SCount,MCount,ECount
)的数量并不是必要的。
相反,我们可以直接通过每个触摸循环,并通过其fingerId跟踪每个单独的触摸,就像@mothil所做的那样。为此,我们需要两个数组来跟踪点击的特征:1)短时间延迟,2)无移动。在下面的数组中,数组索引是fingerId。
private float[] timeTouchBegan;
private bool[] touchDidMove;
我们还需要一个变量来存储所需的触摸时间阈值。在我的测试中,我发现阈值为
0.2f
效果不错。
private float tapTimeThreshold = 0.2f
在
Start()
函数中,我们将初始化这个变量以容纳10个元素,用于10个触点。这可以根据需要修改。
在
Update()
函数中,我们循环遍历每个触摸。如果处于
TouchPhase.Began
状态,则将
timeTouchBegan[fingerIndex]
设置为当前时间;我们还将
touchDidMove[fingerIndex]
设置为false。
如果处于
TouchPhase.Moved
状态,则将
touchDidMove[fingerIndex]
设置为true。
最后,在
TouchPhase.Ended
状态下,我们可以计算出点击时间。
float tapTime = Time.time - timeTouchBegan[fingerIndex];
如果点击时间小于阈值且触摸没有移动,则我们确认这是一个有效的点击。
if (tapTime <= tapTimeThreshold && touchDidMove[fingerIndex] == false)
{
}
完整脚本
以下是完整的类:
public class TapManager : MonoBehaviour
{
private float[] timeTouchBegan;
private bool[] touchDidMove;
private float tapTimeThreshold = 0.2f;
void Start()
{
timeTouchBegan = new float[10];
touchDidMove = new bool[10];
}
private void Update()
{
foreach (Touch touch in Input.touches)
{
int fingerIndex = touch.fingerId;
if (touch.phase == TouchPhase.Began)
{
Debug.Log("Finger #" + fingerIndex.ToString() + " entered!");
timeTouchBegan[fingerIndex] = Time.time;
touchDidMove[fingerIndex] = false;
}
if (touch.phase == TouchPhase.Moved)
{
Debug.Log("Finger #" + fingerIndex.ToString() + " moved!");
touchDidMove[fingerIndex] = true;
}
if (touch.phase == TouchPhase.Ended)
{
float tapTime = Time.time - timeTouchBegan[fingerIndex];
Debug.Log("Finger #" + fingerIndex.ToString() + " left. Tap time: " + tapTime.ToString());
if (tapTime <= tapTimeThreshold && touchDidMove[fingerIndex] == false)
{
Debug.Log("Finger #" + fingerIndex.ToString() + " TAP DETECTED at: " + touch.position.ToString());
}
}
}
}
}
Unity测试
我使用Unity Remote在我的游戏中进行了测试。在下面的截图中,您可以看到我的调试控制台日志。我进行了四指点击。您可以看到0到3号手指进入和离开时没有检测到任何移动。每个手指都被检测到了一次点击,每个点击的位置都会打印到控制台。
![enter image description here](https://istack.dev59.com/dteTN.webp)