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

public class Laser : MonoBehaviour
{
    public List<GameObject> list = new List<GameObject>();
    public Transform firePos;
    public Transform headRot;
    Transform target;
    public LineRenderer line;
    public float damOverTime = 20f;
    public float slowFactor = 0.5f;
    public AudioSource player;
    public AudioClip clip;
    private void Start()
    {
        InvokeRepeating("GetTarget", 0, 0.5f);
    }

    void Update()
    {
        if (target == null)
        {
            line.enabled = false;
            player.Stop();
            return;
        }
        Vector3 tarPos = target.position;
        tarPos.y = headRot.position.y;
        line.enabled = true;
        player.enabled = true;
        headRot.LookAt(tarPos);
        line.SetPositions(new Vector3[] { firePos.position, target.position });
        target.GetComponent<Mon>().GetDam(damOverTime * Time.deltaTime);
        target.GetComponent<Mon>().getSlow(slowFactor);
        if (player.isPlaying)
        {
        }
        else
        {
            player.PlayOneShot(clip);
        }
    }

    void GetTarget()
    {
        float minDis = Mathf.Infinity;
        Transform nearMon = null;
        //MUSTÿλȡǰȰѿܵĿնƳ
        list.RemoveAll(item => item == null);
        foreach (GameObject item in list)
        {
            float dis = Vector3.Distance(transform.position, item.transform.position);
            if (dis < minDis)
            {
                minDis = dis;
                nearMon = item.transform;
            }
        }
        target = nearMon;
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "mon")
        {
            list.Add(other.gameObject);
        }
    }
    private void OnTriggerExit(Collider other)
    {
        if (other.tag == "mon")
        {
            list.Remove(other.gameObject);
        }
    }
}