(Unity)マウスでロックオンした敵をギミックで破壊する

(1)

  • マウスでロックオン

  • ロックオン後、ボタン押しで発射音が鳴る。
  • 0.7秒後に敵の破壊を確認(ギミック;弾は飛んでいない)

 


(スクリプト)

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

public class MouseLook : MonoBehaviour
{
    public Transform player;
    private float mouseSensitivity = 200f;
    private float xRotation = 0;

    public Image aimImage;
    private RaycastHit enemyHit;

    // ★★(敵の破壊)
    public AudioClip shotSound;
    public AudioClip destroySound;
    public GameObject effectPrefab;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

        xRotation -= mouseY;

        xRotation = Mathf.Clamp(xRotation, -90f, 90f);
        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);

        player.Rotate(Vector3.up * mouseX);

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

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

            if(hitName == "Enemy")
            {
                aimImage.color = Color.red;

                // ★★(敵の破壊)
                // 左クリック
                if (Input.GetMouseButtonDown(0))
                {
                    // 発射音を出す
                    AudioSource.PlayClipAtPoint(shotSound, Camera.main.transform.position);

                    // Invokeメソッドで時間差を生み出す
                    Invoke("DestroyEnemy", 0.7f);
                }
            }
            else
            {
                aimImage.color = Color.white;
            }
        }
        else
        {
            aimImage.color = Color.white;
        }
    }

    // ★★(敵の破壊)
    void DestroyEnemy()
    {
        if(enemyHit.transform.gameObject)
        {
            GameObject effect = Instantiate(effectPrefab, enemyHit.point, Quaternion.identity);
            Destroy(effect, 1.0f);
            AudioSource.PlayClipAtPoint(destroySound, transform.position);
        }

        // 破壊すべきものは「Enemy」のTagが付いているものに限定する。
        if(enemyHit.transform.CompareTag("Enemy"))
        {
            Destroy(enemyHit.transform.gameObject);
        }
    }
}