using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

	Animator _animator;
	bool _facingRight = true;
	bool _jump;
	bool _grounded;

	// Use this for initialization
	void Start () {
		_animator = GetComponent<Animator>();
	}
	
	void Update()
	{
        if (Input.GetButtonDown("Fire1"))
        {
            // If the jump button is pressed and the player is grounded and the character is running forward then the player should jump.
            if (_grounded)
            {
                _jump = true;
                _grounded = false;
                _animator.SetBool("Grounded", false);
                _animator.SetTrigger("Jump");
            }
            // if the game is set now to start the character will start to run forward in the FixedUpdate
            else
                _animator.SetTrigger("Start");
	    }
	}

    void OnCollisionEnter2D(Collision2D hit)
    {
        _grounded = true;
		_animator.SetBool("Grounded", true);
    }

	// Update is called once per frame
	void FixedUpdate ()
	{
		float move = Input.GetAxis("Horizontal");

		rigidbody2D.velocity = new Vector2(move * 10, rigidbody2D.velocity.y);
		_animator.SetFloat("Speed", Mathf.Abs(move));

		if(_jump)
		{
			rigidbody2D.AddForce(new Vector2(0f, 200));
			_jump = false;
		}
	
		if(move > 0 && !_facingRight)
			Flip();
		else if(move < 0 && _facingRight)
			Flip();
	}

	void Flip()
	{
		_facingRight = !_facingRight;
		Vector3 scale = transform.localScale;
		scale.x *= -1;
		transform.localScale = scale;
	}
}
