(Unity)砲塔が敵をロックオンすると、照準器のサイズを変化させる

(仕組み)

  • 砲塔の先端からRayを飛ばす。

  • このRayが敵を捕捉した時、照準器の画像サイズを変化させる。


(スクリプト)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AimController_ShotShell : MonoBehaviour
{
    public GameObject aimImage;

    void Update()
    {
        // レイの可視化
        Debug.DrawRay(transform.position, transform.forward * 1000, Color.green);

        Ray ray = new Ray(transform.position, transform.forward);

        RaycastHit hit;

        if (Physics.Raycast(ray, out hit))
        {
            if (hit.collider.CompareTag("EnemyB"))
            {
                // 大きさを変化させる
                aimImage.transform.localScale = new Vector3(1.5f, 1.5f, 1.5f);
            }
            else
            {
                aimImage.transform.localScale = new Vector3(1, 1, 1);
            }
        }
        else
        {
            aimImage.transform.localScale = new Vector3(1, 1, 1);
        }
    }
}

(設定)

  • Create Emptyで作成したShotShellオブジェクト(発射台)にスクリプトを追加

  • 空欄にAimイメージをドラッグ&ドロップ

 

  • 設定が完了したらゲームを再生して確認しましょう。