カメラからのレイのもっとも一般的な使用方法は レイキャスト をシーンに向かって実行することです。レイキャストは仮想の “レーザービーム” をシーンのコライダーにヒットするまで、その原点からレイに沿って発します。次に、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.
}
}
}