unity2D 射线检测

在网上搜了好多关于2D射线检测的,点击屏幕,利用射线检测点击到的物体是否是我想要的物体(物体上添加了2d碰撞器)。

在网上搜到的都是一些这样的答案:

RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
 if (hit.collider != null)
 {
     Debug.Log("clicked object name is ---->"+ hit.collider.gameObject);
 }           
           

但是结果没有什么用,根本没反应,最后翻墙google了一下,找到了一个正确答案,这里记录一下:

void Update () {

        if (Input.GetMouseButtonDown(0))
        {
            Vector3 mousePos = Input.mousePosition;
            mousePos.z = 10;

            Vector3 screenPos = Camera.main.ScreenToWorldPoint(mousePos);

            RaycastHit2D hit = Physics2D.Raycast(screenPos, Vector2.zero);

            if (hit)
            {
                print(hit.collider.name);
            }
        }   
}

 

发布了38 篇原创文章 · 获赞 16 · 访问量 10万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章