ブログ

照準器の作成(砲弾の発射ポイントからRayを飛ばす)

(スクリプト)

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

public class Aim_XXX : MonoBehaviour
{
    public Image aimImage;
    public GameObject shotShell;

    private void Update()
    {
        // shotShellオブジェクトの位置からRayを飛ばす
        Ray ray = new Ray(shotShell.transform.position, shotShell.transform.forward);

        // 確認用コード
        Debug.DrawRay(shotShell.transform.forward, shotShell.transform.forward * 100, Color.red);

        RaycastHit hit;

        if (Physics.Raycast(ray, out hit))
        {
            string hitName = hit.transform.gameObject.tag;

            if (hitName == "Enemy")
            {
                aimImage.color = new Color(1.0f, 0.0f, 0.0f, 1.0f);
            }
            else
            {
                aimImage.color = new Color(0.0f, 1.0f, 1.0f, 1.0f);
            }
        }
        else
        {
            aimImage.color = new Color(0.0f, 1.0f, 1.0f, 1.0f);
        }
    }
}