using UnityEngine;
using System.Collections;

public class FirstPersonOwlCamera : MonoBehaviour {

	private float owlSpeed = 80.0f;
	private float owlTurnSpeed = 1.0f;
	private float owlAcceleration = 2.0f;
	private float roll = 0.0f;
	private float rollSpeed = 0.6f;
	private float maxRoll = 0.3f;

	private float angle;
	private float speed = 0.0f;

	public void Start() {
		angle = Random.Range (0, 2.0f * Mathf.PI);
	}


	public void Update() {
		float dt = Time.deltaTime;

		// process input
		if (Input.GetKey ("left")) {
			angle += owlTurnSpeed * dt;
			roll += rollSpeed * dt;
		}
		if (Input.GetKey ("right")) {
			angle -= owlTurnSpeed * dt;
			roll -= rollSpeed * dt;
		}
		if (!Input.GetKey ("left") && !Input.GetKey ("right") && Mathf.Abs (roll) > 0.01f) {
			float prevRoll = roll;
			roll += -Mathf.Sign (roll) * rollSpeed * dt;
			if (prevRoll*roll < 0.0f) roll = 0.0f; // we reached 0 and went over
		}
		if (Input.GetKey ("up")) {
			speed += owlAcceleration;
		}
		if (Input.GetKey ("down")) {
			speed -= owlAcceleration;
		}
		if (speed > owlSpeed) speed = owlSpeed;
		if (speed < 0) speed = 0;
		if (Mathf.Abs (roll) > maxRoll) {
			roll = maxRoll * Mathf.Sign (roll);
		}

		// update movement
		transform.position = transform.position + new Vector3(speed * Mathf.Cos (angle) * dt, 0.0f, speed * Mathf.Sin(angle) * dt);

		// rotate
		transform.rotation = Quaternion.identity;
		transform.RotateAround(Vector3.down, angle);

		// finally, rotate around our forward vector in the turn direction
		Vector3 dir = new Vector3(Mathf.Cos (angle), 0.0f, Mathf.Sin (angle));
		transform.RotateAround(dir, roll);
	}
}
