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

public class PlaneScript : MonoBehaviour {

    public Rigidbody2D rb;
    private float speed = -2f;
    public Animator anim;

    public GameObject explosion;

    private int countHit;

    public GameObject[] prefabs;

	void Start () {
        rb = GetComponent<Rigidbody2D>();
        countHit = 0;
	}
	
	void Update () {
        rb.velocity = transform.right * speed;
	}

    void OnTriggerEnter2D(Collider2D collision) {
        if (collision.tag == "PlayerBullet") {
            countHit += 1;
        }

        if (countHit == 2) {
            anim.SetTrigger("Death");
        }

        if (countHit == 3) {
            GameObject explode = (GameObject)Instantiate(explosion, transform.position, transform.rotation);
            Destroy(this.gameObject);
            SpawnCoin();
            Destroy(explode, 1.3f);
        }
    }
    
    void SpawnCoin() {
        GameObject player = GameObject.Find("Player");
        if (player != null) {
            int randPrefabs = Random.Range(0, 10);
            GameObject coins = Instantiate(prefabs[randPrefabs], transform.position, transform.rotation) as GameObject;
            Vector2 direction = player.transform.position - coins.transform.position;
            coins.GetComponent<CoinScript>().SetCoinDirection(direction);
        }
    } 
}
