using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static UnityEngine.GraphicsBuffer;

public class Standard : MonoBehaviour
{
    List<GameObject> list = new List<GameObject>();
    public GameObject bulletPre;
    public Transform head;
    public Transform firePos;
    public float fireInter;
    float timer = 0;
    Transform target;
    public AudioSource player;
    public AudioClip clip;
    void Start()
    {
        InvokeRepeating("GetTarget", 0, 0.5f);
    }

    void Update()
    {
        if (target == null)
        {
            return;
        }
        Vector3 pos =target.position;
        pos.y = head.position.y;
        head.LookAt(pos);
        timer += Time.deltaTime;
        if (timer >= fireInter)
        {
            GameObject bulletObj = Instantiate(bulletPre, firePos.position, Quaternion.identity);
            bulletObj.GetComponent<Bullet>().SetTarget(target);
            timer = 0;
            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.gameObject.tag == "mon")
        {
            list.Add(other.gameObject);
        }
    }
    private void OnTriggerExit(Collider other)
    {
        if (other.gameObject.tag == "mon")
        {
            list.Remove(other.gameObject);
        }
    }
}
