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

public class Astroid : MonoBehaviour {

    Rigidbody2D astroid_rigidbody; 

	// Use this for initialization
	void Start () {
        
	}

    private void OnEnable()
    {
        astroid_rigidbody = GetComponent<Rigidbody2D>();
        astroid_rigidbody.AddTorque(Random.Range(-20.0f, 20.0f));
        Vector2 dir = new Vector3(0.0f, 0.0f, 0.0f) - transform.position;
        astroid_rigidbody.AddForce(dir * 2.0f);
    }

    private void OnCollisionEnter2D(Collision2D other)
    {
        if(other.gameObject.tag == "Earth")
        {
            AstroidSpawner.instance.EarthHit();
            StartCoroutine(Despawn());
        }
        else if(other.gameObject.tag == "Player")
        {
            AstroidSpawner.instance.earthHP -= 5;
            StartCoroutine(Despawn());
        }
        else if(other.gameObject.tag == "Laser")
        {
            Destroy(other.gameObject);
            StartCoroutine(Despawn());
        }
    }



    IEnumerator Despawn()
    {
        GetComponent<Animator>().SetTrigger("Dead");
        yield return new WaitForSecondsRealtime(0.5f);
        astroid_rigidbody.velocity = Vector3.zero;
        astroid_rigidbody.angularVelocity = 0.0f;
        gameObject.SetActive(false);
        AstroidSpawner.instance.DespawnAstroid(this.gameObject);
        yield return null;
    }

}


