来自摄像机的射线最常见的用途是将射线投射 (raycast) 到场景中。射线投射从原点沿着射线方向发送假想的“激光束”,直至命中场景中的碰撞体。随后会返回有关该对象和 RaycastHit 对象内的投射命中点的信息。这是一种基于对象在屏幕上的图像来定位对象的非常有用的方法。例如,可使用以下代码确定鼠标位置处的对象:
using UnityEngine;
using System.Collections;
public class ExampleScript : MonoBehaviour {
public Camera camera;
void Start(){
RaycastHit hit;
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit)) {
Transform objectHit = hit.transform;
// Do something with the object that was hit by the raycast.
}
}
}