using UnityEngine;
using System.Collections;

public class SquirrelMovement : MonoBehaviour {
	public GameObject goTarget;
	Quaternion qTarget;
	Vector3 v3Target;
	bool bArrived, bHit;
	// Use this for initialization
	void Start () {

//		qTarget = Quaternion.Euler(new Vector3(0.0f, 180.0f, 0.0f));
//		v3Target = new Vector3(-1.0f, 0.25f, 14.69f);
		qTarget = goTarget.transform.rotation;
		v3Target = goTarget.transform.position;
		goTarget.transform.parent = null;
		bHit = false;

//		this.transform.position = new Vector3 (6.0f, -0.25f, 15.0f);

	}
	
	// Update is called once per frame
	void Update () {
		if (Vector3.Distance(transform.position, v3Target) < 3f && !bArrived) {
			this.transform.rotation = Quaternion.Slerp (transform.rotation, qTarget, Time.deltaTime * 3);
		}
		if(!bArrived)
		{
			transform.position += (v3Target - transform.position).normalized * Time.deltaTime * 4;
			
		}			
//		if(!bHit)
//		{
			RaycastHit hit;
			if (Physics.SphereCast(transform.position-transform.up/5, 0.5f, -transform.up, out hit, 5)) {
				transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(Vector3.Cross(transform.right, hit.normal), hit.normal), Time.deltaTime * 5.0f);
				if(hit.distance < .1f) 
				{
					transform.position += transform.up*Time.deltaTime*1;
				}else if (hit.distance > .2f)
				{
					transform.position -= transform.up*Time.deltaTime*1;
				}
			}

//		}			

		if (Vector3.Distance(transform.position, v3Target) < .3f) 
		{
//			print ("Arrived!");
			bArrived = true;
		}
		if(!rigidbody.isKinematic)
		{
			bHit = true;
		}

	}
}
