using UnityEngine;
using System.Collections;

public class CMouseOrbit : MonoBehaviour {

	public Transform target;
	public float distance = 10f;

	public float xSpeed = 250f;
	public float ySpeed = 120f;

	public float yMinLimit = -20;
	public float yMaxLimit = 80;

	float x = 0f;
	float y = 0f;

	void Start() {
		x = transform.eulerAngles.x;
		y = transform.eulerAngles.y;

		if (GetComponent<Rigidbody>()) {
			GetComponent<Rigidbody>().freezeRotation = true;
		}
	}

	void LateUpdate() {
		if (target) {
			x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
			y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
			distance += Input.mouseScrollDelta.y * 0.2f;
		}

		y = ClampAngle(y, yMinLimit, yMaxLimit);

		Quaternion rotation = Quaternion.Euler(y, x, 0);
		Vector3 position = rotation * new Vector3(0, 0, -distance) + target.position;

		transform.rotation = rotation;
		transform.position = position;
	}

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

}