視錐台を理解する のセクションではカメラビューのどの点でもワールド空間の線に対応することを説明しました。その線を数学的に表現することが便利なときがあるので、Unity はこれを レイ オブジェクトという形で提供しています。レイはつねにビューの点に対応するので、Camera クラスは ScreenPointToRay と ViewportPointToRay 関数を提供しています。この 2 つの違いは ScreenPointToRay が点をピクセル座標として表すのに対して、ViewportPointToRay は正規化された座標を 0..1 の範囲 (ビュー上で 0 が左または下、1 が右または上) で表します。この各々の関数は、原点とそこからの向きを表すベクトルから構成されるレイを返します。レイはカメラの transform.position ではなくニアクリップ面を起点としています。
カメラからのレイのもっとも一般的な使用方法は レイキャスト をシーンに向かって実行することです。レイキャストは仮想の “レーザービーム” をシーンのコライダーに衝突するまで、その原点からレイに沿って発します。次に、レイキャストがヒットしたオブジェクトとヒットした点に関する情報が、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;
// レイに当たったオブジェクトで何かをする
}
}
}
画面位置に対応するレイを取得してカメラをそれに沿って移動させると便利な場合があります。例えば、ユーザーがオブジェクトをマウスで選択して、同じ画面位置をマウスで “維持” しながらズームインしたい場合があるかもしれません (例えば、戦略マップなどで便利かもしれません)。これを行うためのコードは比較的容易です。
using UnityEngine;
using System.Collections;
public class ExampleScript : MonoBehaviour {
public bool zooming;
public float zoomSpeed;
public Camera camera;
void Update() {
if (zooming) {
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
float zoomDistance = zoomSpeed * Input.GetAxis("Vertical") * Time.deltaTime;
camera.transform.Translate(ray.direction * zoomDistance, Space.World);
}
}
}
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.