using UnityEngine;
using System.Collections;

public class BulletScript : MonoBehaviour
{
    public Transform explosionPrefab;
    private GameObject camera;
    private Vector3 oldCameraPos;
	// Use this for initialization
	void Start ()
	{
	    camera = GameObject.FindGameObjectWithTag("MainCamera");
	    oldCameraPos = new Vector3(camera.transform.position.x,camera.transform.position.y,camera.transform.position.z);
	}

    void OnDestroy()
    {
        PlayerScript.ammoCount -= 1;
        camera.transform.position = oldCameraPos;
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        Destroy(gameObject,1f);
        Instantiate(explosionPrefab,transform.position,Quaternion.identity);
        Invoke("Disappear",0.01f);
    }

    void Disappear()
    {
        gameObject.SetActive(false);
    }
	// Update is called once per frame
	void Update ()
	{

	    var speed = transform.GetComponent<Rigidbody2D>().velocity;
	    var horizontalDir = new Vector2(1, 0);
	    var angle = Vector2.Angle(speed, horizontalDir);
        Vector3 cross = Vector3.Cross(speed, horizontalDir);
	    if (cross.z > 0)
	    {
	        angle = 360 - angle;
	    }
	    transform.eulerAngles = new Vector3(0,0,angle);

        camera.transform.position = new Vector3(transform.position.x, camera.transform.position.y, camera.transform.position.z);
	}
}
