
var realTower : GameObject;
private var groundLayerMask = 1 << 8;
private var obstacleLayer = 9;
private var colliderCount = 0;
private var mat : Material;

function Start ()
{
	mat = GetComponentInChildren(Renderer).material;
	mat.color.r = 0;
	mat.color.g = 1;
	mat.color.b = 0.25;
}

function Update () 
{
	// Get camera ray
	var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

	// Check for intersection with terrain
	var hit : RaycastHit;
	if (Physics.Raycast(ray, hit, Mathf.Infinity, groundLayerMask))
	{
		// Move tower to intersection point
		transform.position = hit.point;
	}
	
	if (colliderCount == 0 && Input.GetButtonDown("Fire1"))
	{
		var t : GameObject = Instantiate(realTower);
		t.transform.position = transform.position;
		Destroy(gameObject);
	}
}

function OnTriggerEnter (other : Collider)
{
	if (other.gameObject.layer == obstacleLayer)
	{
		colliderCount += 1;
		mat.color.r = 0.8;
		mat.color.g = 0;
		mat.color.b = 0;
	}
}

function OnTriggerExit (other : Collider)
{
	if (other.gameObject.layer == obstacleLayer)
	{
		colliderCount -= 1;
		if (colliderCount <= 0)
		{
			colliderCount = 0;
			mat.color.r = 0;
			mat.color.g = 1;
			mat.color.b = 0.25;
		}
	}
}