using UnityEngine;
using System.Collections;

public class GunControl : MonoBehaviour 
{
	public float speed = 30f;
	public float force = 50;
	public float torqueForce = 50f;
	public GameObject currentBall;
	public GameObject ballPrefab;
	float zAngle = 0f;
	
	void Start()
	{
		zAngle = transform.rotation.eulerAngles.z;	
	}
	
	void RotateByEuler()
	{
		transform.rotation = Quaternion.Euler(new Vector3(0f, 0f, zAngle));
	}
	
	void RotateByQuaternion()
	{
		transform.rotation = Quaternion.Lerp(Quaternion.Euler(Vector3.zero), 
			Quaternion.Euler(Vector3.forward * 90f),
			zAngle / 90f);
	}
	
	void Update()
	{
		if(Input.GetKey(KeyCode.DownArrow))
		{
			if(zAngle >= 90)
			{
				zAngle = 90;
				return;
			}
			
			zAngle += Time.deltaTime * speed;
			RotateByEuler();
		}
		
		else if(Input.GetKey(KeyCode.UpArrow))
		{
			if(zAngle <= 0)
			{
				zAngle = 0;
				return;
			}
			
			zAngle -= Time.deltaTime * speed;
			RotateByEuler();
		}
		
		else if(Input.GetButton("Fire1"))
		{
			if(currentBall != null)
				return;
			
			currentBall = (GameObject)Instantiate(ballPrefab, transform.position, Quaternion.identity);
			currentBall.rigidbody.AddTorque(Vector3.forward * torqueForce);
			Vector2 direction = transform.rotation * new Vector3(force, 0f, 0f);
			currentBall.rigidbody.AddForce(direction, ForceMode.Impulse);
			//audio.PlayOneShot((AudioClip)Resources.Load("Sounds/fire", typeof(AudioClip)));
		}
	}
}
