3D世界屏蔽UI的响应事件

3D世界中屏蔽UI的响应事件

在Unity游戏开发中,我们会经常遇到这样一个问题:拖拽3D场景来预览当前的世界。即通过拖拽鼠标来控制相机的位置。但是场景中一般都会有UI界面悬浮在最上层。

当我们滑动UI界面上面的滚动列表的时候,会发现此时的场景会跟着移动。这是我们不想看到的。正确的结果应该是拖动场景的时候相机才移动,这才符合我们的设定。因此就需要一个接口来判断当前鼠标是否点击到了UI上面。

public bool IsPointerOverGameObject()
    {
        if (Input.GetMouseButton(0) 
            || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began))
        {
#if UNITY_EDITOR
            if (EventSystem.current.IsPointerOverGameObject())
                return true;
#else
            if (Input.touchCount > 0)
            {
                 int fingerId = Input.GetTouch(0).fingerId;
                 if (EventSystem.current.IsPointerOverGameObject(fingerId))
                 {
                     return true;
                 }
            }
#endif
        }
        return false;
    }

上面的函数接口,如果返回true就表明当前鼠标点击了UI。

猜你喜欢

转载自blog.csdn.net/onelei1994/article/details/106141715