//This script raycasts from the barrel of the weapon, along the forward (local z) axis, it also takes the rotation along the y axis from the camera to do vertical
//aiming, this allows the gun to not have to rotate on the model (it can easily be disabled if gun rotation is implemented). It also draws the crosshair on the screen
//and will draw gizmos of the line of fire.
var weaponTarget : Transform;
var weaponObject : Transform;
var crosshairImage : Texture2D;
var range = 50.0;

function Start()
{
}

function FixedUpdate () 
{
	//Get direction of barrel
	var dir = weaponObject.forward;
	
	//Use Y rotation of camera
	dir.y = transform.forward.y;
	
	//Project maximum range position for the weapon's target along the barrel's direction
	weaponTarget.position = weaponObject.position + (dir * range);

	//Check for collision between the weapon and the target (not the other way around) and move
	//the target to the collision point (e.g. the point a bullet would hit after leaving the barrel).
	var hit : RaycastHit;
	if (Physics.Linecast(weaponObject.position, weaponTarget.position, hit))
	{
		weaponTarget.position = hit.point;
	}
} 

function OnGUI()
{
	if(camera.enabled)
	{
		//This function merely draws the cursor, the image is moved so it is centred at the position.
		//Note that the Y is inverted as the GUI co-ordinate system has an inverted Y Axis
		var pos:Vector3 = camera.WorldToScreenPoint(weaponTarget.position);
		GUI.DrawTexture(Rect(pos.x - (crosshairImage.width / 2), (Screen.height - (pos.y + (crosshairImage.height / 2))), crosshairImage.width, crosshairImage.height), crosshairImage);
	}
}

//function OnDrawGizmosSelected()
function OnDrawGizmos()
{	
	Gizmos.color = Color.red;
	Gizmos.DrawLine(weaponObject.position, weaponTarget.position);
	Gizmos.DrawIcon(weaponTarget.position, "CrosshairIcon.psd");
}