1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Unity認定試験対策:Raycast

Posted at

Raycastとは?

Unityの認定試験の練習問題で頻出の機能のひとつが Raycast(レイキャスト) です。
Raycastは 「ある点から特定方向に飛ばす見えない直線でColliderに当たるかを調べる」 仕組みです。

クリック判定・弾丸判定・視線検出 などの問題に登場します。

試験で問われやすいポイント

  • OnMouseDown は内部的に Raycast を使用している
  • Ignore Raycast レイヤーに設定したオブジェクトはヒットしない
  • Physics.Raycast の引数(Ray / 距離 / LayerMask など)が問われやすい
  • RaycastHit で当たり情報(位置・距離・オブジェクト)を取得できる

コード例

void Update()
{
    // ① マウス位置からカメラに向かってRayを飛ばす
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

    // ② 当たった情報を格納
    RaycastHit hit;

    // ③ 100ユニット以内で判定
    if (Physics.Raycast(ray, out hit, 100f))
    {
        Debug.Log("当たったオブジェクト: " + hit.collider.gameObject.name);
    }
}

RaycastHitで取得できる情報

プロパティ 内容
hit.collider 当たったCollider
hit.point 衝突した座標
hit.normal 当たった面の法線ベクトル
hit.distance 発射点からの距離

レイヤー制御

特定レイヤーだけRaycast

int layerMask = LayerMask.GetMask("Enemy");
if (Physics.Raycast(ray, out hit, 100f, layerMask))
{
    Debug.Log("敵にヒット!");
}

Ignore Raycast レイヤー

  • このレイヤーに設定したオブジェクトは Raycast から無視される
  • 「大きいColliderを無視して小さいColliderだけOnMouseDownで反応させる」 などのケースで正解になる

まとめ(試験対策)

  • Raycast = 見えない直線で当たり判定
  • 用途:クリック判定 / 弾丸 / 視線
  • OnMouseDown は Raycast を使う
  • Ignore Raycast レイヤーで不要なColliderを無視できる

公式リファレンス

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?