UGUI檢測射線穿透的方法

  • 一種是通過EventSystem的RaycastAll檢測
  • 一種是通過GraphicRaycaster的Raycast檢測

這裏寫圖片描述
這裏寫圖片描述
+ 兩種方法,代碼如下

 public static bool IsPointerOverUIObject()
 {

        PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
        eventDataCurrentPosition.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);

        List<RaycastResult> results = new List<RaycastResult>();
        EventSystem.current.RaycastAll(eventDataCurrentPosition, results);

        return results.Count > 0;
    }


public static bool IsPointerOverUIObject(Canvas canvas, Vector2 screenPosition)
{
        PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
        eventDataCurrentPosition.position = screenPosition;

        GraphicRaycaster uiRaycaster = canvas.gameObject.GetComponent<GraphicRaycaster>();
        List<RaycastResult> results = new List<RaycastResult>();
        uiRaycaster.Raycast(eventDataCurrentPosition, results);

        return results.Count > 0;
}

參考:http://www.cnblogs.com/fly-100/p/4570366.html
https://github.com/k79k06k02k/Utility

發佈了37 篇原創文章 · 獲贊 20 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章