两种不同写法的射线检测
1.获取鼠标点击的物体
if (Input.GetMouseButtonDown(0))
{
Ray ray = MainCamera.ScreenPointToRay(Input.mousePosition); //以摄像机为原点创建一条射线RaycastHit hit;
if (Physics.Raycast(ray, out hit)) //点击到了带有碰撞体的物体
{
Transform clickObjTrans = hit.transform; //获取点击的物体
if (clickObjTrans.name == "Manager")
{
}
Debug.DrawLine(ray.origin, hitInfo.point,Color.red);//画出射线
}
}
2.获取鼠标点击的物体
if (Input.GetMouseButtonDown(0))
{
// 获取鼠标点击位置
//创建射线;从摄像机发射一条经过鼠标当前位置的射线
Ray ray = firstCamera.ScreenPointToRay(Input.mousePosition);RaycastHit hitInfo = new RaycastHit(); //发射射线
if (Physics.Raycast(ray, out hitInfo))
{
//获取碰撞点的位置
if (hitInfo.collider.name == "Ground")
{
}
Debug.DrawLine(ray.origin, hitInfo.point, Color.red);
}
}
本文介绍了两种使用Unity实现射线检测的方法,通过鼠标点击来获取被点击的对象,并演示了如何利用射线检测来与场景中的物体进行交互。
525

被折叠的 条评论
为什么被折叠?



