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] Rayを飛ばす

Posted at

簡単にではあるけれど、Rayを飛ばしてみる

動作環境

・Windows11
・UnityEditorのバージョン 2022.3.48.f1
・プロジェクト Universal 3D

スクリプトを書く

Rayにコライダーがヒットしたらコンソールにhit!と出力するスクリプトを書く
スクリプト名は自身の分かりやすい、目的にあった名前で大丈夫でしょう。今回はEnemyRayとしておく。

EnemyRay
using UnityEngine;

public class EnemyRay : MonoBehaviour
{
    [SerializeField]
    [Tooltip("rayの距離を指定する")]
    private float rayDis = 5.0f;
    [SerializeField]
    [Tooltip("rayの原点を指定する")]
    private Vector3 rayOrigin;


    void FixedUpdate()
    {
        //Rayにコライダーがヒットしたらコンソールにhit!と出力する
        if (Physics.Raycast(rayOrigin, transform.forward * rayDis, rayDis))
        {
            Debug.Log("hit!");

        }
    }

    //RayをGizmosに描画する
    private void OnDrawGizmos()
    {
        Debug.DrawRay(rayOrigin, transform.forward * rayDis, Color.red);
    }
}

SerializeFieldで、Inspector上からRayの原点と飛ばす、描画する長さとを設定できるようにしておくと便利かも。また、OnDrawGizmos()でScene上にRayを描画しておくとデバッグ時に作業の効率化が図れるため、積極的に使いたいところ。

Sceneの様子

image.png

スクリプトが動くことを確認する

  1. 適当なオブジェクトを作り、先ほど書いたEnemyRayをアタッチ
  2. 再度、適当なオブジェクトを作り、Rayに重なるように配置
    image.png
  3. 実行する

実行すると画像右下のようにhit!の文字が出力される
image.png

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?