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

public class ProjectileBehaviour : MonoBehaviour
{

    private float speed = 800f;
    private Rigidbody2D rb;
    private Vector2 velocity = Vector2.zero;
    private float despawnTime = 3f;
    private SpriteRenderer spriteRenderer;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        spriteRenderer = GetComponent<SpriteRenderer>();
    }

    // Update is called once per frame
    void Update()
    {
        rb.velocity = velocity;
        if (velocity.x > 0)
        {
            spriteRenderer.flipX = false;
        }
        else
        {
            spriteRenderer.flipX = true;
        }

    }

    private IEnumerator Despawn()
    {
        var t = despawnTime;
        while (t > 0)
        {
            t -= Time.deltaTime;
            yield return null;
        }
        Destroy(gameObject);
        yield return null;
    }

    public void Shoot(Vector2 origin, Vector2 direction)
    {
        transform.position = origin;
        velocity = direction * speed;
        StartCoroutine(Despawn());
    }
    

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Enemy")
        {
            var t = collision.transform;
            if (t.name == "Feet")
            {
                t = t.parent;
            }
            t.GetComponent<LucertolaBehaviour>().Stun();
            Destroy(gameObject);
        }
        if (collision.tag == "Environment")
        {
            Destroy(gameObject);
        }
    }
}
