【问题标题】:Unity3D: C# - Can't seem to handle single/double/ hold touches correctlyUnity3D:C# - 似乎无法正确处理单/双/按住触摸
【发布时间】:2018-07-13 01:43:05
【问题描述】:

使用 Unity3D 2018.2

正在尝试单击、双击和按住。

存在的问题:

单击:有时不会注册我的单击

双击:每次双击设备时都会调用 8 次

Triple Tap:双击被调用 10 次,Triple 被调用 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");
        }
    }
}

【问题讨论】:

    标签: c# android ios unity3d touch


    【解决方案1】:

    这里有一些不同的地方。

    1) 你在打电话

        float tapBeginTime = 0;
        float tapEndedTime = 0;
    

    在每个 Touch 元素的开头。意思是你的支票

    (tapEndedTime - tapBeginTime) < 0.03f
    

    永远不会通过,因为在您设置 tapEndedTime = Time.time; 时,tapBeginTime 将被重置为 0

    如果您想在每次触摸的基础上跟踪这些时间,我建议创建一个字典,将触摸的fingerIds 映射到它们的开始时间。您不需要记录每次触摸的tapEndedTime,因为它应该足以作为根据需要计算的局部变量。

    2) 我不能 100% 确定这一点,但您可能还需要检查 if (touch.phase == TouchPhase.Ended) 以及 if (touch.tapCount == 2) 检查,以获得准确的结果。我知道我个人过去曾遇到过没有明确检查的问题。

    3) 你也在做一个if (touch.phase == TouchPhase.Moved) 检查inside 一个if (touch.phase == TouchPhase.Ended) 块。我会让你弄清楚这个:)

    我希望这些要点可以帮助您解决一些迫在眉睫的问题。一旦解决了这些表面问题,我建议您探索进一步优化生成代码的方法。 祝你好运!

    【讨论】:

      猜你喜欢
      • 2017-09-10
      • 2017-10-05
      • 2015-10-14
      • 1970-01-01
      • 2021-01-09
      • 2021-04-29
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      相关资源
      最近更新 更多