using UnityEngine;
using System.Collections;

public class Spelunker : MonoBehaviour
{
		int jumps = 0;
	
		int MAXJUMPS = 2;
	
		bool released = true;
		float height;
		
		Animator anim;

		// Use this for initialization
		void Start ()
		{
				height = Camera.main.ViewportToWorldPoint (Vector3.one).y + renderer.bounds.extents.y;
				anim = GetComponent<Animator> ();
				anim.SetInteger ("JumpState", 2);
		}
	
		// Update is called once per frame
		void Update ()
		{
				if (Input.anyKey) {
						if (released && jumps < MAXJUMPS) {
								collider2D.enabled = false;
								
								rigidbody2D.velocity = Vector2.zero;
								rigidbody2D.AddForce (Vector2.up * 800);
								
								released = false;
								
								anim.SetInteger ("JumpState", 1);
								
								jumps++;
						}
				} else {
						released = true;
				}
				
				if (rigidbody2D.velocity.y < -2f) {
						collider2D.enabled = true;
						
						anim.SetInteger ("JumpState", 2);
						
						if (jumps == 0) {
								jumps = MAXJUMPS;
						}
				}
				
				if (transform.position.y < -height) {
						Vector2 newPos = transform.position;
					
						newPos.y = height;
					
						transform.position = newPos;
				}
		}

		void OnCollisionEnter2D (Collision2D other)
		{
				released = true;
				jumps = 0;
				anim.SetInteger ("JumpState", 0);
		}
}
