using UnityEngine;
using System.Collections;

public class RhinoFollower : MonoBehaviour {

	private Rhino rhino;

	private Quaternion q = Quaternion.identity;
	private Vector3 dir;

	public void init(Rhino rhino) {
		this.rhino = rhino;

		// we position ourselves behind the rhino
		q = rhino.transform.rotation;
	}
	
	// Update is called once per frame
	void Update () {
		float dt = Time.deltaTime;

		// the new angle
		Quaternion newQ = rhino.transform.rotation;

		// rotate a bit up
		Vector3 dir = newQ * Vector3.forward;
		newQ = Quaternion.AngleAxis (45.0f, Vector3.Cross (Vector3.up, dir)) * newQ;

		// interpolate the angle to the new angle
		q = Quaternion.Lerp (q, newQ, 1.0f * dt);

		// compute the direction of the quaternion
		dir = q * Vector3.forward;
		float distance = Data.rhinoCameraDistance;

		// rotate the camera in the same direction
		transform.rotation = q;
		
		// position ourselves
		Vector3 loc = rhino.transform.position - dir * distance;

		// offset the loc randomly
		float maxSpeedEffect = 0.3f;
		float speed = Interpolate.EaseInCubic(0.0f, maxSpeedEffect, rhino.speed, Data.rhinoMaxSpeed);
		loc += new Vector3(Random.Range (-speed, speed), Random.Range (-speed, speed), Random.Range (-speed, speed));

		// position
		transform.position = loc;
	}
}
