处理未在 UI 上启动的触摸

Handle touches not started on the UI

我寻求一种方法来处理未在 Unity 引擎中的 UI 元素上开始的触摸。

这样做的目的是对一个"map"进行旋转、平移和放大(以后都这样称呼)。但是,如果触地事件发生在任何 UI 元素上,则应由该 UI 元素而不是地图处理。

我认为这样的例子之一是 Google 的地图 android 应用程序。

我尝试了几种解决方案:

I seek a way to handle touches that do not start on UI elements in Unity Engine ...But if the touch down event is on any of the UI elements it shall be handled by that UI element instead of the map.

IsPointerOverGameObject function is used to simplify this. If it returns false, do you panning, rotation. If it returns true then the mouse is over any UI element. It is better and easier to use this than to use a boolean variable that is modifed by every UI element. Use OnPointerClick to detect events on the UI(map). See 了解更多信息。

void Update()
{
    checkTouchOnScreen();
}

void checkTouchOnScreen()
{
    #if UNITY_IOS || UNITY_ANDROID || UNITY_TVOS
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
    {
        //Make sure finger is NOT over a UI element
        if (!EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
        {
            OnSCreenTouched();
        }
    }
    #else
    // Check if the left mouse button was clicked
    if (Input.GetMouseButtonDown(0))
    {
        //Make sure finger is NOT over a UI element
        if (!EventSystem.current.IsPointerOverGameObject())
        {
            OnSCreenTouched();
        }
    }
    #endif
}


void OnSCreenTouched()
{
    Debug.Log("Touched on the Screen where there is no UI");

    //Rotate/Pan/Zoom the camera here
}

I would like if possible to not use "if"s to check if the touch is on any another UI element as this might prove a real performance issue

没有 if 语句,没有其他方法可以做到这一点。即使是上面的简单答案也需要它。它不会 影响性能。