RaycastShot

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

public class RaycastShot : MonoBehaviour {

    public int gunDamage = 1;
    public float fireRate = 0.25f;
    public float weapnRange = 50f;
    public float hitForce = 300f;
    public Transform gunEnd;

    private Camera fpsCam;
    private WaitForSeconds shotDuration = new WaitForSeconds(0.07f);
    private AudioSource gunAudio;
    private LineRenderer laserLine;
    private float nextFire;

	void Start () {
        print("ok1");
        laserLine = GetComponent<LineRenderer>();
        gunAudio = GetComponent<AudioSource>();
        fpsCam = GetComponent<Camera>();
        print("ok2");
    }
	
	void Update () {
		if(Input.GetButtonDown("Fire1") && Time.time > nextFire)
        {
            nextFire = Time.time + fireRate; // fireRate分の時間は発射できない。
            StartCoroutine(ShotEffect());

            Vector3 rayOrigin = fpsCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0));

            RaycastHit hit;

            laserLine.SetPosition(0, gunEnd.position);

            if(Physics.Raycast(rayOrigin, fpsCam.transform.forward, out hit, weapnRange))
            {
                laserLine.SetPosition(1, hit.point);

                ShootableBox health = hit.collider.GetComponent<ShootableBox>();

                if(health != null)
                {
                    health.Damage(gunDamage);
                }

                if(hit.rigidbody != null)
                {
                    // 「hit.normal」の使い方をマスターする。
                    hit.rigidbody.AddForce(-hit.normal * hitForce);
                }
            }
            else
            {
                laserLine.SetPosition(1, rayOrigin + (fpsCam.transform.forward * weapnRange));
            }
        }
    }

    private IEnumerator ShotEffect()
    {
        gunAudio.Play();

        laserLine.enabled = true;

        yield return shotDuration;

        // 0.07秒後にレーザーラインが消える。(0.07秒間待機して後、レーザーラインが消える。)
        laserLine.enabled = false;
    }


    //    private IEnumerator ShotEffect()
    //    {
    //        // Play the shooting sound effect
    //        gunAudio.Play();

    //        // Turn on our line renderer
    //        laserLine.enabled = true;

    //        //Wait for .07 seconds
    //        yield return shotDuration;

    //        // Deactivate our line renderer after waiting
    //        laserLine.enabled = false;
    //    }
}