[英]Unity3D: C# - Can't seem to handle single/double/ hold touches correctly
使用Unity3D 2018.2
试图获得单击,双击和按住键。
存在的问题:
单次点击:有时不会注册我的单次点击
双击:每次我双击设备时都会被呼叫8次
三连击:连击10次,然后三连击9次
这是我的代码,如果您对C#和Unity不熟悉,那么我就无法完成这样一个简单的任务,请您多加帮助
private void handleTouchTypes()
{
foreach (Touch touch in Input.touches)
{
float tapBeginTime = 0;
float tapEndedTime = 0;
// Touches Began
if (touch.phase == TouchPhase.Began)
{
tapBeginTime = Time.time;
}
// Touches Ended
if (touch.phase == TouchPhase.Ended)
{
tapEndedTime = Time.time;
// Single Touch: for 0.022f of a Second
if (touch.tapCount == 1 && ((tapEndedTime - tapBeginTime) < 0.03f))
{
Debug.Log("Single Touch");
}
// Hold Touch: within half a second .5f to 1f
if (touch.phase == TouchPhase.Moved && touch.deltaPosition.magnitude < 0.02f && (tapEndedTime - tapBeginTime) >= 0.5f && (tapEndedTime - tapBeginTime) <= 1f)
{
Debug.Log("Holding Touch");
}
}
if (touch.tapCount == 2)
{
// Double Tap
Debug.Log("Double Tap");
}
if (touch.tapCount >= 3)
{
// Triple Tap
Debug.Log("3 Touches and/or more");
}
}
}
这里有些不对劲。
1)你在打电话
float tapBeginTime = 0;
float tapEndedTime = 0;
在每个Touch元素的开头。 表示您的支票
(tapEndedTime - tapBeginTime) < 0.03f
永远不会过去,因为tapBeginTime
将在您设置tapEndedTime = Time.time;
重置为0
tapEndedTime = Time.time;
。
如果您想基于每次触摸跟踪这些时间,我建议创建一个字典,将触摸的fingerId
映射到其开始时间。 您无需记录每次触摸的tapEndedTime
,因为它足以作为根据需要计算的局部变量。
2)我对此不是100%的确定,但是除了if (touch.tapCount == 2)
检查之外,您可能还需要检查if (touch.phase == TouchPhase.Ended)
,以获得准确的结果。 我知道我个人过去没有遇到过明确检查的问题。
3)你也做了if (touch.phase == TouchPhase.Moved)
检查内部 if (touch.phase == TouchPhase.Ended)
块。 我会让你知道这一点:)
希望这些观点能帮助您解决一些近期的问题。 解决了这些表面问题后,建议您进一步探索优化最终代码的方法。 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.