Handle touches not started on the UI

后端 未结 1 1501
粉色の甜心
粉色の甜心 2020-12-02 01:26

I seek a way to handle touches that do not start on UI elements in Unity Engine.

The purpose of this is rotating, panning and zooming in on a \"map\" (it shall be ca

相关标签:
1条回答
  • 2020-12-02 01:57

    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.

    The 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 this for more information.

    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

    There is no other way to do this without an if statement. Even the simple answer above requires it. It doesn't affect the performance.

    0 讨论(0)
提交回复
热议问题