【Unity3d】Ray射线初探-射线的原理及用法

时间:2023-03-10 02:50:43
【Unity3d】Ray射线初探-射线的原理及用法

http://www.xiaobao1993.com/231.html

射线是一个无穷的线,开始于origin并沿着direction方向。
当射线碰到物体后。它就会停止发射。

在屏幕中拉一个CUBE,并用鼠标点击它

using UnityEngine;
using System.Collections; public class TestRay : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButton(0))
{
Debug.Log("xxxxxxxxxxxxxxxxxxxxxx"); Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//从摄像机发出到点击坐标的射线
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
Debug.DrawLine(ray.origin, hitInfo.point);//划出射线,在scene视图中能看到由摄像机发射出的射线
GameObject gameObj = hitInfo.collider.gameObject;
if (gameObj.name.StartsWith("Cube") == true)//当射线碰撞目标的name包含Cube,执行拾取操作
{
Debug.Log(gameObj.name);
}
}
}
}
}