Unity基础入门分享

Unity射线检测3d,2D,正交透视。

2019-04-26  本文已影响17人  betterplace

使用射线功能制作点击物体获取物体名字。可以做简单点击相应。

3D射线检测,Camera 在正交模式与透视模式皆可使用

 void Update()

    {

       Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

       RaycastHit hitInfo;

       if (Physics.Raycast(ray, out hitInfo))

       {

           //划出射线,只有在scene视图中才能看到

           Debug.DrawLine(ray.origin, hitInfo.point);

           GameObject gameObj = hitInfo.collider.gameObject;

           Debug.Log("click object name is " + gameObj.name);

            //点击相应,删除被点击物体↓

            //Destroy(gameObj);

       }

       else

       {

           Debug.Log("null");

       }      

}

2D射线检测只在正交下可用。

  void Update()

    {

        Ray ray =Camera.main.ScreenPointToRay(Input.mousePosition);

        RaycastHit2D hit =Physics2D.Raycast(ray.origin, ray.direction);

        if (hit)

        {

            Debug.Log(hit.transform.name);

            Debug.DrawLine(ray.origin,hit.point);

        }

        else

        {

            Debug.Log("null");

        }

    }

上一篇 下一篇

猜你喜欢

热点阅读