using UnityEngine;
using System.Collections;

public class findnearest_object : MonoBehaviour {

	public GameObject cannon;
	private float nextfire = 0.0f;
	public float fireRate = 1f;
	
	public AudioClip shotSound;
	public AudioSource audio;
	

	public GameObject shot;
	public Transform shotSpawn;
	
	void Update(){
		
		cannon.transform.LookAt (FindClosestEnemy().transform);
		launchRocket();
	}

	GameObject FindClosestEnemy(){
		GameObject[] gos;
		gos = GameObject.FindGameObjectsWithTag ("player");
		GameObject cloest = null;
		float distance = Mathf.Infinity;
		Vector3 position =transform.position;
		foreach(GameObject go in gos){
			Vector3 diff =go.transform.position - position;
			float curDistance =diff.sqrMagnitude;
			if(curDistance<distance){
				cloest =go;
				distance=curDistance;
			}
		}

		return cloest;
	}


	void launchRocket(){
		if (Time.time > nextfire){
			nextfire = Time.time + fireRate;
			audio.PlayOneShot(shotSound,1f);
			Instantiate(shot,shotSpawn.position,shotSpawn.rotation);
		}
 	}
}
