using UnityEngine;
using System.Collections;

public class CarScript : MonoBehaviour {

	public Transform[] wayPoints;

	int currentWaypoint;
	float speed;
	float fSlider;
	public float fSpeedForward, fRotationY;
	// Use this for initialization
	void Start () {

		currentWaypoint = 1;
		speed = 5.0f;
	}
	
	// Update is called once per frame
	void Update () {

//		rigidbody.velocity = Vector3.zero;
//		if (currentWaypoint < wayPoints.Length) Drive();
		DriveAngry();
	}

	void Drive() {
		
		Vector3 target = wayPoints[currentWaypoint].position;
		target.y = transform.position.y;
		
		Vector3 dir = target - transform.position;
		
		if(dir.magnitude == 0f) {
			currentWaypoint++;
			fSlider = 0;
			
		} else {
			var rotation = Quaternion.LookRotation(target - transform.position);
			transform.rotation = Quaternion.Slerp(transform.rotation, rotation, fSlider);
			//			rigidbody.velocity = dir.normalized*speed*Time.deltaTime;
			transform.position = Vector3.Lerp(wayPoints[currentWaypoint-1].position, target, fSlider);
			fSlider += Time.deltaTime;
		}
	}
	void DriveAngry() 
	{
		transform.rotation = Quaternion.Euler(new Vector3(transform.rotation.eulerAngles.x,
		                                                  transform.rotation.eulerAngles.y + fRotationY*Time.deltaTime,
		                                                  transform.rotation.eulerAngles.z));
		RaycastHit hit;
		if (Physics.SphereCast(transform.position, 0.5f, -transform.up, out hit, 15)) {
			transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(Vector3.Cross(transform.right, hit.normal), hit.normal), Time.deltaTime * 10.0f);
			if(hit.distance < 0.45f) 
			{
				transform.position += transform.up*Time.deltaTime*3;
			}else if (hit.distance > .5f)
			{
				transform.position -= transform.up*Time.deltaTime*3;
			}
		}

		transform.position += transform.forward*Time.deltaTime*fSpeedForward;
	}

}
