using UnityEngine;
using System.Collections;
[RequireComponent (typeof (Rigidbody2D))]

public class Cricket : MonoBehaviour {

	public int speed=2;
	public Vector2 direction;

	public bool moveRight=true;

	public float timeInAir;
	public float maxAirTime;
	public float originalXPosition;
	public Rigidbody2D body;
	public bool idle;
	private float gravityScale = 0;

	// Use this for initialization
	void Start () {
		body = this.gameObject.GetComponent<Rigidbody2D> ();
		originalXPosition = this.transform.position.x; 
		gravityScale = body.gravityScale;

	}
	
	// Update is called once per frame
	void Update () {

			CricketRoam ();
		}
	


	void CricketRoam()
	{
		if (timeInAir>maxAirTime+5 &&!idle) {
			timeInAir = 0;
			body.velocity = Vector2.zero;
			Hop ();
		}

		timeInAir += Time.deltaTime;
		if (timeInAir > maxAirTime) {
			HeadDown ();
						}

	}
	public void Hop()
	{
		if (moveRight)
			direction.x = 1;
		else
			direction.x = -1;
		body.AddForce (direction * speed);

	}
	public void HeadDown()
	{
		
		//body.AddForce (Vector2.down * speed);
		moveRight = IsNextDirectionRight ();
	}

	public bool IsNextDirectionRight()
	{
		if (originalXPosition > gameObject.transform.position.x) {
			return true;
		} else
			return false;


	}


}
