﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {

	private bool jumping = false;
	private bool grounded = false;
	private bool doubleJump = false;
	private bool doubleJumping = false;

	private Rigidbody2D rigidBody;
	public Transform groundCheck;
	public LayerMask layerMask;

	public float acceleration = 100f;
	public float maxSpeed = 10f;
	public float jumpSpeed = 500f;

	// Use this for initialization
	void Awake () {
		rigidBody = GetComponent<Rigidbody2D> ();
	}

	// Update is called once per frame
	void Update() {
		grounded = Physics2D.Linecast(transform.position, groundCheck.position, layerMask);

		if (Input.GetButtonDown("Jump"))
		{
			if (grounded) {
				jumping = true;
				doubleJump = true;
			} else if (doubleJump) {
				doubleJumping = true;
				doubleJump = false;
			}
		}
	}

	//Called in fixed time intervals, frame rate independent
	void FixedUpdate()
	{
		float moveH = Input.GetAxis ("Horizontal");

		if (rigidBody.velocity.x * moveH < maxSpeed) {
			rigidBody.AddForce (Vector2.right * moveH * acceleration);
		}

		if (Mathf.Abs (rigidBody.velocity.x) > maxSpeed) {
			Vector2 vel = new Vector2 (Mathf.Sign (rigidBody.velocity.x) * maxSpeed, rigidBody.velocity.y);
			rigidBody.velocity = vel;
		}

		if (jumping) {
			rigidBody.AddForce(new Vector2(0f, jumpSpeed));
			jumping = false;
		}
		if (doubleJumping) {
			rigidBody.velocity = new Vector2 (rigidBody.velocity.x, 0);
			rigidBody.AddForce(new Vector2(0f, jumpSpeed));
			doubleJumping = false;
		}
			
	}
}
