22
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UnityのRaycastを可視化する

Posted at

#やりたい事
画面をタップした際に、画面上のキャラクター等をタップしたかどうか判定するのは一般的にRaycastを使うが、その飛ばしたRayをデバッグ目的で可視化したい。

#Debug.DrawRay()を使う

if (Input.GetMouseButtonDown (0)) {
  float distance = 100;	// 飛ばす&表示するRayの長さ
  float duration = 3;	// 表示期間(秒)

  Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
  Debug.DrawRay (ray.origin, ray.direction * distance, Color.red, duration, false);

  RaycastHit hit = new RaycastHit ();
  if (Physics.Raycast (ray, out hit, distance)) {
    GameObject hitObject = hit.collider.gameObject;
    // (以下略)
  }
}

これでGameビューをクリックすると、Sceneビューに謎の赤いビームが表示されます。下記が実行例です(何も無いので分かり辛いですが、右下のGameビューを適当にクリックしまくった状態です)。

image

#ドキュメント
Unity - スクリプトリファレンス: Debug.DrawRay
Unity - スクリプトリファレンス: Physics.Raycast

22
20
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
22
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?