【问题标题】:Unity Touch Count ignore Ui inputUnity Touch Count 忽略 Ui 输入
【发布时间】:2020-06-13 19:01:10
【问题描述】:

我有一个简单的游戏,当用户触摸屏幕时,玩家会跳跃。我已经使用 touchCount 实现了这一点,因为当 touchCount =1 然后玩家跳跃时。但问题是屏幕上有一个按钮,所以当用户按下一个按钮时,touchCount 被验证并且玩家跳转。那么如何仅在用户触摸屏幕的非 ui 部分时才启用播放器跳转。提前致谢。

【问题讨论】:

    标签: c# unity3d game-development


    【解决方案1】:

    您可以使用 EventSystem.current.IsPointerOverGameObject 添加检查是否在 UI 上发生触摸

    API 的使用示例:

    // Check if there is a touch
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
    {
        // Check if finger is over a UI element
        if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
        {
            Debug.Log("Touched the UI");
        }
    }
    

    使用Linq Where,您可以将此条件用作过滤器,以便仅考虑那些未通过 UI 使用的触摸,例如

    // Get all touches that are NOT over UI
    var validTouches = Input.touches.Where(touch => !EventSystem.current.IsPointerOverGameObject(touch.fingerId)).ToArray();
    
    // This is basically a shortcut for writing something like
    //var touchesList = new List<Touch>();
    //foreach(var touch in Input.touches)
    //{
    //    if(!EventSystem.current.IsPointerOverGameObject(touch.fingerId))
    //    {
    //         touchesList.Add(touch);
    //    } 
    //}
    //var validTouches = touchesList.ToArray();
    
    if(validTouches.Length == 1)
    {
        // Your jump here
    }
    

    【讨论】:

    • 链接中提到了它,但最好在顶部提到需要using System.Linq;
    【解决方案2】:

    这是安卓版的吧?>

    我建议使用统一内置的 ui 按钮来定义活动位置,我认为这应该自动适用于 android。

    或者你可以为触摸的位置做一个 if 语句,所以如果位置低于或高于某个点,它将不会激活。

    【讨论】:

    • 这并不能解决问题,因为每个设备都有自己的分辨率。为一台设备做上述事情对其他设备没有好处。
    • 比id推荐使用unity内置的Ui按钮
    • 用于跳跃的UI按钮?
    • 是的,比让按钮运行一个函数跳转
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    相关资源
    最近更新 更多