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

public class Enemy : MonoBehaviour
{
    public ParticleSystem explosion;
    public ParticleSystem explosionDebris;
    public Transform landingPoint;
    public GameObject body;
    public float flyingSpeed;

    private void Update()
    {
        //Debug.DrawRay(transform.position, launchDirection, Color.red);
    }
    public void SetLandingPoint(Transform landingPoint)
    {
        this.landingPoint = landingPoint;
        gameObject.transform.LookAt(landingPoint);
        
    }

    void SpawnFinished()
    {
        StartCoroutine("Launch", 0.01f);
    }

    IEnumerator Launch()
    {
        yield return new WaitForSeconds(.1f);
        gameObject.GetComponent<Rigidbody>().velocity = gameObject.transform.forward * flyingSpeed;
    }

    public void IsShot(float distance)
    {
        float destroyDelay = Mathf.Sqrt(distance)/(500/5);
        Debug.Log(distance+" : "+destroyDelay);
        StartCoroutine(Destroy(destroyDelay));
    }

    private IEnumerator Destroy(float waitTime)
    {
        gameObject.GetComponent<Rigidbody>().velocity = gameObject.transform.forward * (flyingSpeed / 3);
        yield return new WaitForSeconds(waitTime);
        body.SetActive(false);
        explosion.Emit(100);
        explosionDebris.Emit(40);        
        yield return new WaitForSeconds(3f);
        Destroy(gameObject);
    }
}
