Unity中 创建射线的两种方法

通过摄像机

  • 我们通过摄像机让屏幕点转化为射线
ray = Camera.main.ScreenPointToRay(Input.mousePosition);

直接new出来

Ray ray = new Ray(V3 origin, V3 dir);  //指定原点和方向
Physics.Raycast(ray, out hit); //进行碰撞检测
//hit当中包含了很多碰撞信息
//hit.point 获取碰撞点
//hit.normal 碰撞面的法线方向,即与碰撞面垂直的线
//hit.distance 碰撞点到射线原点的距离
// hit.textureCoord 纹理坐标 可以用于纹理或者弹痕绘制,如果对象没有Meshcolider则返回null  

为什么要创建射线

  • 我们通过Input.mousePosition获取到的V3坐标是在Z方向是0,我通过log打印之后,只是在x,y 方向上有输出
  • Input.mousePosition 是实时获取鼠标点的位置,如果仅仅是想要在点击时获取其位置,那么要加一个if语句
  • 我们可以通过hit.point获取鼠标点击的三维空间的坐标
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Input.GetKeyDown(0))
{
    if(Physics.Raycast(ray, out hit))
    {
        agent.SetDestination(hit.point);
    }
}

你可能感兴趣的:(UGUI)