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

public class FPSShoot : MonoBehaviour
{
    public Rigidbody grenadePrefab;
    public AudioClip laserAudio;

    public float pushForce = 100f;
    public float fireRate = 0.25f;
    public float laserRange = 50f;
    public ParticleSystem muzzleFlash;
    public GameObject hitEffect;
    public Text crateNumber;

    private float nextFire = 1f;
    private Camera fpsCam;
    private LineRenderer laserLine;

    private IEnumerator ShootEffect(RaycastHit hit){
        laserLine.enabled = true;
        int framNum = 10;

        Vector3 p = transform.position;
        Vector3 q;
        Vector3 step = (hit.point - p) / framNum;
        for(int i = 0; i < framNum; i++){
            q = p + step;
            laserLine.SetPosition(0, p);
            laserLine.SetPosition(1, q);
            p = q;
            yield return new WaitForSeconds(0.01f);
        }
        laserLine.enabled = false;

        if(hit.transform.gameObject.GetComponent<TakeDamage>() != null){
            hit.transform.gameObject.GetComponent<TakeDamage>().Damage();
        }else{
            GameObject dust = Instantiate(hitEffect, 
                                            hit.point, 
                                            Quaternion.LookRotation(hit.normal)
                                            );
            Destroy(dust, 2.0f);
        }
    }

    // Start is called before the first frame update
    void Start()
    {
        fpsCam = Camera.main;
        laserLine = gameObject.GetComponent<LineRenderer>();
        laserLine.enabled = false;
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Escape)){
            Application.Quit();
        }

        GameObject[] gos = GameObject.FindGameObjectsWithTag("Crate");
        crateNumber.text = "Boxed Remaining:" + gos.Length.ToString();


        if(Input.GetMouseButtonDown(0) && nextFire < Time.time){
            nextFire = Time.time + fireRate;

            Vector3 rayOrigin = fpsCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0.5f));
            RaycastHit hit;
            //smoke & fire
            muzzleFlash.Play();
            AudioSource.PlayClipAtPoint(laserAudio, transform.position);
            if(Physics.Raycast(rayOrigin, fpsCam.transform.forward, out hit, laserRange)){
                StartCoroutine(ShootEffect(hit));
            }
        }

        if(Input.GetMouseButtonDown(1) && nextFire < Time.time){
            nextFire = Time.time + fireRate;
            Rigidbody cloneRb = Instantiate(grenadePrefab, transform.position, Quaternion.identity);
            cloneRb.AddForce(fpsCam.transform.forward * pushForce);
            Destroy(cloneRb.gameObject, 3.0f);
        }
    }



    
}
//检查上述代码，为何我的crateNumber;这一行会报错？Invalid token ';' in class, record, struct, or interface member declaration