Unity 相机/物体发射射线--简单小记

(1)从相机发射射线

功能:鼠标点击屏幕发射射线,打印射线打到的物体的名字。

相机发射射线:Ray ray =Camera.main.ScreenPointToRay(Input.mousePosition);

 public void RayFormCamer()//从相机发射射线
    { 
        RaycastHit hit;
        Ray ray =Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray,out hit))
        {
            Debug.Log(hit.transform.name);//打印射线碰撞到的物体名字
            
        }
    }

(2)从物体发射射线

功能:场景内物体发射射线,到检测到碰撞体时返回物体的名字。

物体发射射线:Vector3 V3 = transform.TransformDirection(Vector3.forward);

该脚本需挂在需要射线检测的物体上

如果需要打印射线必须设置射线长度,不打印射线则不需要填写射线距离

if (Physics.Raycast(transform.position,V3,out hit,"射线检测的距离"))

Debug.DrawLine(“起点”,“终点,“颜色”,”显示时间“);//打印射线,该射线仅Scene窗口可见(如果需要打印射线必须设置射线长度,颜色,显示时间为可选项)

public void RayForGame()//从物体发射射线
    {
        RaycastHit hit;
        Vector3 V3 = transform.TransformDirection(Vector3.forward);
        if (Physics.Raycast(transform.position,V3,out hit,20))
        {
            Debug.Log(hit.transform.name+hit.point);//打印射线碰撞到的物体
            Debug.DrawLine(transform.position, hit.point, Color.red,1);//打印射线(射线由脚本所在物体到达射线碰撞到的物体)
        }
    }

Scene窗口打印射线示意图

猜你喜欢

转载自blog.csdn.net/qq_36361484/article/details/131788385
今日推荐