Unity 射线检测(2D&&3D)

时间:2025-02-21 13:22:59

Canvas上2D物体检测更新

private Canvas canvas;

    void Start()
    {
        canvas = FindObjectOfType<Canvas>();
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Click2DItem();
        }
    }

    /// <summary>
    /// 点击2d物体,主要是用canvas的事件系统
    /// </summary>
    public void Click2DItem()
    {
        PointerEventData pointerEventData = new PointerEventData(EventSystem.current);
        pointerEventData.position = Input.mousePosition;
        GraphicRaycaster gr = canvas.GetComponent<GraphicRaycaster>();
        List<RaycastResult> results = new List<RaycastResult>();
        gr.Raycast(pointerEventData, results);
        if (results.Count != 0)
        {
            //这里如果需要对特定的2d物体做点击,我一般是给对应的2d物体添加各自的tag
            Debug.Log(results[0].gameObject.name);
            
        }
    }

被点击的物体上必须有collider组件
3D物体检测:

//鼠标右键点击
if (Input.GetMouseButtonUp(1))
        {
            // 点击鼠标左键抬起时发射一条射线
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitInfo;
            if (Physics.Raycast(ray, out hitInfo))
            {
                Debug.Log("click object name is ---->" + hitInfo.collider.gameObject.name);
            }

            //在半径为5的球形范围内的所有3d物体都会被检测到
            Collider[] colliders = Physics.OverlapSphere(Vector3.zero, 5.0f);
            if (colliders.Length > 0)
            {
                for (int i = 0; i < colliders.Length; i++)
                {
                    Debug.Log("第二种方式---click object name is ---->" + colliders[i].gameObject.name);
                }
            }
        }

Sprite 2D物体检测

//左
if (Input.GetMouseButtonUp(0))
        {
            // 第一种方法,与3d检测类似
            RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
            if (hit.collider != null)
            {
                Debug.Log("clicked object name is ---->"+ hit.collider.gameObject);
            }

            // 第二种方法,overlap检测物体重叠的点
            Collider2D[] collider2Ds = Physics2D.OverlapPointAll(Camera.main.ScreenToWorldPoint(Input.mousePosition));
            if (collider2Ds.Length > 0)
            {
                for (int i = 0; i < collider2Ds.Length; i++)
                {
                    Debug.Log("overlap object point,The name is ---->" + collider2Ds[i].gameObject.name);
                }

                //foreach (Collider2D item in collider2Ds)
                //{
                //    ("overlap object point,The name is ---->" + collider2Ds[i].);
                //}
            }
        }