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

public class Enemy : MonoBehaviour{
    public GameObject player;
    public float time, time3, countdown, count;
    public bool active; 
    public Vector3 target;
    public GameObject projetil;
    void Start(){
        time = 3f;
        time3 = 12f;
        countdown = time;
    }
    void Update(){
        Timer();
        Aim();
        if(time3 > 0f){
            time3 -= 1f * Time.deltaTime;
        }else{
            if(count < 3){
                time3 = 0.5f;
                count++;
                shoot();
            }else{
                count = 0;
                time3 = 12f;
            }
            
        }
    }
    void Timer(){
        if(active){
            if(countdown > 0f){
                countdown-= 1f * Time.deltaTime;
            }else{
                countdown = time;
                if(player != null && player.GetComponent<Player>().move){
                    shoot();
                }
            }
        }
    }
    void Aim(){
        if(player != null){
            target = player.transform.position;
            var dir = target - transform.position;
            var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
            transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
            if(transform.rotation.z > 0.75){
                GetComponent<SpriteRenderer>().flipY = true;
            }else{
                GetComponent<SpriteRenderer>().flipY = false;
            }
        }
    }
    void shoot(){
        GameManager.Instance.audios.PlayOneShot(GameManager.Instance.clips[2]);
        GameObject o = Instantiate(projetil);
        o.transform.position = transform.position;
        o.transform.rotation = transform.rotation;
    }
}