/*
	Thomas Baca
	Targeting Nearest Object
	09/12/10
*/

//Creates variables to be used
//ClosestDist gets the distance that is nearest to the 
//players current position or guns current position
//Field of View or ShootingAngleDistance
//A gameobject that initialized distance and game tags
//TurretRotation Speed is how fast the turret will rotate towards its target
var closestDist = Mathf.Infinity; 
var attackRange = 30.0;
var shootAngleDistance = 10.0;
var closest: GameObject; 
var turretRotationSpeed = 0.0;

//Main Function that updates every cpu cycle/////////////////////////
function Update () 
{    
		//Creates an array of gameobjects that have the tag "waypoints"
		var waypoints: GameObject[] = GameObject.FindGameObjectsWithTag("waypoint");  

		//Loops through the array of objects and calculating distances
		//if the distances is less that the closest object in the array
		//Set the new closest to the current distances
		//if the distances exceeds the closest distance than reset closest by adding 100
		//For some reason this affects the targeting so by adding 100 every milisecond 
		//it goes to the nearest target instead of looking at the last closest object.
		for(waypoint in waypoints)
		{
			var dist = (transform.position - waypoint.transform.position ).sqrMagnitude;   
			
			if(dist <= closestDist)
			{
				closestDist = dist;
				closest = waypoint;       
			}else
			{
				closestDist += 100;
			}
		
			/////////////////////////////////////////////////////////////////////
			//for debuging purposes///////////////////////////////////////////////
			//Keep in comments unless closestDist needs to be known
			/*
			if(Input.GetKeyDown("t"))
			{
			print("ClosestDist: " + closestDist);
			}
			*/
		
			///////////////////////////////////////////////////
			//If the closest object is less than the assigned range 
			//Rotate turret to the objects x,y,z and if 
			//turret is looking at the object send fire message
			//to the firing script within the object firing.
			if(closestDist <= attackRange && closest != null)
				{
				//creates a variable of targeting point 
				//it is assigned the closest object vector
					if(closest == null)
						return;
				
				var targetPoint = closest.transform.position;
			
				var targetRotation = Quaternion.LookRotation ( targetPoint - transform.position , Vector3.up);
				transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * turretRotationSpeed);

				// If we are almost rotated towards target - fire one clip of ammo
				var forward = transform.TransformDirection(Vector3.forward);
				var targetDir = closest.transform.position - transform.position;
			
				//If the turrents front "Z" is within a certain shooting angle and closest target 
				//tag is waypoint send message to firing script to "FIRE"
				if (Vector3.Angle(forward, targetDir) < shootAngleDistance && closest.gameObject.tag == "waypoint")
				SendMessage("Fire");
				}
			
		}

}