using UnityEngine;
using System.Collections;

[AddComponentMenu("Camera-Control/3rd Person CS (Bernard)")]
public class Camera3rdPerson_Bernard : MonoBehaviour 
{
	// Public
	public Transform target;
	public float xSpeed = 250f;
	public float ySpeed = 120f;
	public float zSpeed = 250f;
	
	public float yMinLimit = -20f;
	public float yMaxLimit = 80f;
	public float minDistance = 5f;
	public float maxDistance = 100f;
	public float distance = 10f;
	public float heightOffset = 10f;	
	
	// Private 
	private Vector3 angles = Vector3.zero;
	private float x = 0f;
	private float y = 0f;
	private float z = 0f;			
 	private Vector3 vHeight = Vector3.zero;
	
	// Initialization
	void Start () 
	{		
		angles = transform.eulerAngles;
		x = angles.x;
		y = angles.y;
		z = distance;	
	 	vHeight.y = heightOffset;
		
		// Make the rigid body not change rotation
		if(rigidbody)
			rigidbody.freezeRotation = true;
	}
	
	// Update is called once per frame
	void Update () 
	{
		if(!camera.enabled)
			return;
		
		if(target)
		{
	    	// Only update the camera with mouse input if the user is pressing the
	    	// right mouse button.  This allows the user to use the mouse without
	    	// driving the camera			
			if(Input.GetButton("Fire2"))
			{
				x += Input.GetAxis("Mouse X") *  xSpeed * 0.02f;
				y -= Input.GetAxis("Mouse Y") *  ySpeed * 0.02f;
			}
			
			// Always update zoom with mouse wheen
			z -= Input.GetAxis("Mouse ScrollWheel") * zSpeed * 0.02f;
			
			y = ClampAngle(y, yMinLimit, yMaxLimit);
			z = ClampAngle(z, minDistance, maxDistance);
			
			transform.rotation = Quaternion.Euler(y, x, 0f);
			transform.position = transform.rotation * (z * Vector3.back) + 
				target.position + vHeight;
		}
	}
	
	private static float ClampAngle(float angle, float min, float max)
	{
		while(angle < -360f) 
			angle += 360f;
		while(angle > 360f)
			angle -= 360f;
		return Mathf.Clamp(angle, min, max);
	}
}
