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

public class EnemyTank : MonoBehaviour {

    public static EnemyTank instance;

    public Rigidbody2D rb;
    public float speed = -1;
    private int countHit;

    public GameObject explosion;
   
    public GameObject coin;

	void Start () {
        rb = GetComponent<Rigidbody2D>();
        countHit = 0;
        MakeInstance();
	}

    void MakeInstance() {
        if (instance == null) {
            instance = this;
        }
    }
	
	void Update () {
        rb.velocity = transform.right * speed;
	}

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

        if (countHit == 3) {
            GameObject explode = (GameObject)Instantiate(explosion, transform.position, transform.rotation);
            Destroy(this.gameObject);
            SpawnCoin();
            Destroy(explode, 1.3f);
        }

        if (collision.tag == "PlayerShield") {
            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) {
            GameObject coins = Instantiate(coin, transform.position, transform.rotation) as GameObject;
            Vector2 direction = player.transform.position - coins.transform.position;
            coins.GetComponent<CoinScript>().SetCoinDirection(direction);
        }
    }
}
