//This script used in conjunction with a collider and a camera will make sure
//the camera specified (or found as a child of the object this script is attached to),
//points towards a target.

//The target to look out for and check for collision with the trigger volume, if not
//specified it will find the first object with a character controller.
var targetObject:GameObject;

//The camera that will be used, the camera's position will not be moved only its' rotation
//will be changed. If this is not specified the script will search for a camera in the node's
//children.
var zoneCamera:Camera;

//Whether or not to track the player with the camera, i.e. follow it around when the player
//is in the camera zone
var trackPlayer:boolean = false;

//This is an optional variable for tracking a different target when the target object enters
//the trigger volume, for example the player's head.
var trackTarget:Transform = null;

function Start()
{
	if(zoneCamera == null)
	{
		zoneCamera = gameObject.GetComponentInChildren(Camera);
		if(zoneCamera == null)
			Debug.LogError("Camera not set or found under hierachy!");
	}
	
	if(trackPlayer)
	{
		if(trackTarget == null)
		{
			if(targetObject)
			{
				trackTarget = targetObject.transform;
			}
			else
			{
				var cc:CharacterController = FindObjectOfType(CharacterController);
				if(cc != null)
					trackTarget = cc.transform;
				else
					Debug.LogWarning("Playing tracking turned on but no character controller found in the scene and no transform manually supplied.");
			}
		}
	}
	
	if(targetObject == null)
	{
		if(trackTarget != null)
			targetObject = trackTarget.gameObject;
		else
			Debug.LogError("No target object supplied and no player found in the scene!");
	}
	
	zoneCamera.enabled = false;
	zoneCamera.GetComponent(AudioListener).enabled = false;
}

function Update()
{
	if(trackPlayer)
	{
		if(trackTarget != null)
			zoneCamera.transform.LookAt(trackTarget);
	}
}

function OnTriggerEnter(collider:Collider)
{
	if(collider.gameObject == targetObject || collider.attachedRigidbody.gameObject == targetObject)
	{
		CameraManager.instance.SetActiveCamera(zoneCamera);
	}
}

function OnTriggerExit(collider:Collider)
{
	if(collider.gameObject == targetObject || collider.attachedRigidbody.gameObject == targetObject)
	{
		CameraManager.instance.RevertToMainCamera();
	}
}
@script RequireComponent(Collider)