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

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)
                //{
                //    Debug.Log("overlap object point,The name is ---->" + collider2Ds[i].gameObject.name);
                //}
            }
        }

  • 15
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值