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

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

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");

        }

    }

更多unity2018的功能介绍请到paws3d爪爪学院查找。链接https://www.paws3d.com/,也可以加入unity学习讨论群935714213

近期更有资深开发人士直播分享unity开发经验,详情请进入官网或加入QQ群了解

猜你喜欢

转载自blog.csdn.net/qq_35037137/article/details/89602780