var target : Transform;

var xSpeed = 250.0;
var ySpeed = 120.0;
var zSpeed = 250.0;

var yMinLimit = -20;
var yMaxLimit = 80;
var minDistance = 5;
var maxDistance = 100;
var distance = 10.0;
var heightOffset = 1.0;

private var x = 0.0;
private var y = 0.0;
private var z = 0.0;
private var vHeight : Vector3;

@script AddComponentMenu("Camera-Control/3rd Person (David)")

function Start () 
{
    var angles = transform.eulerAngles;
    x = angles.y;
    y = angles.x;
    z = distance;
    vHeight = Vector3(0.0, heightOffset, 0.0);

	// Make the rigid body not change rotation
   	if (rigidbody)
		rigidbody.freezeRotation = true;
}

function LateUpdate () 
{
	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.02;
	        y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;
        }
        
        // Scroll Wheel is independent of mouse buttons
        z -= Input.GetAxis("Mouse ScrollWheel") * zSpeed * 0.02;
 		
 		y = ClampAngle(y, yMinLimit, yMaxLimit);
 		z = ClampAngle(z, minDistance, maxDistance);
 		       
        var rotation = Quaternion.Euler(y, x, 0);
        var position = rotation * Vector3(0.0, 0.0, -z) + target.position;
        
        transform.rotation = rotation;
        transform.position = position + vHeight;
    }
}

static function ClampAngle (angle : float, min : float, max : float) 
{
	if (angle < -360)
		angle += 360;
	if (angle > 360)
		angle -= 360;
	return Mathf.Clamp (angle, min, max);
}