解决ugui穿透ui点击到游戏对象上的问题

来源:互联网 发布:学大教育网络办公系统 编辑:程序博客网 时间:2024/04/27 20:39

网上很多方法,在pc下是可以的,但是到了安卓手机上,还是会穿透ugui去触发射线对精灵的碰撞事件。这里找到一个办法让ugui在安卓和ios上不会被穿透,是2段代码


先声明一个类

//通过画布上的 GraphicRaycaster 组件发射射线    public bool IsPointerOverUIObject(Canvas canvas, Vector2 screenPosition)    {        //实例化点击事件        PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);        //将点击位置的屏幕坐标赋值给点击事件        eventDataCurrentPosition.position = screenPosition;        //获取画布上的 GraphicRaycaster 组件        GraphicRaycaster uiRaycaster = canvas.gameObject.GetComponent<GraphicRaycaster>();        List<RaycastResult> results = new List<RaycastResult>();        // GraphicRaycaster 发射射线        uiRaycaster.Raycast(eventDataCurrentPosition, results);        return results.Count > 0;    }


然后在点击事件中做pc与移动端的判断。有的事件只有移动端有

 void Update()    {        if (Input.GetMouseButton(0))        {            //pc端            if (!(Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer))            {                //如果点击带ugui则不做任何处理                if (EventSystem.current.IsPointerOverGameObject())                {                    return;                }            }            else//移动端            {                if (GameObject.Find("ShiBingInfoCanvas") != null)//面板存在就判断                {                    //传递画布组件,传递触摸手势坐标                    if (IsPointerOverUIObject(GameObject.Find("ShiBingInfoCanvas").GetComponent<Canvas>(), Input.GetTouch(0).position))                    {                        return;                    }                }            }                        //获得鼠标点击屏幕位置            Vector3 ms = Input.mousePosition;            //将屏幕位置转换为射线            Ray ray = Camera.main.ScreenPointToRay(ms);            //用来记录射线碰撞信息            RaycastHit hit;            ////产生射线            bool iscast = Physics.Raycast(ray, out hit);            if (iscast)            {            //    //如果射中目标,记录射线碰撞点            //    m_targetPos = hitinfo.point;                if (hit.transform.gameObject.name == "p1_1")//碰到开始游戏                {                    ShiBingUICanvas.SetActive(true);                    GameInstance.GetInstance.UpdateUI(GameInstance.GetInstance.ShiBing1);                                    }                else if (hit.transform.gameObject.name == "p2_2")//碰到开始游戏                {                    ShiBingUICanvas.SetActive(true);                    GameInstance.GetInstance.UpdateUI(GameInstance.GetInstance.ShiBing2);                }            }        }    }


0 0