using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

	public AudioClip JumpClip;

	Animator _animator;
	Rigidbody2D _rigidBody2d;
	bool _facingRight = true;
	bool _grounded;

	// Use this for initialization
	void Start ()
	{
		_animator = GetComponent<Animator>();
		_rigidBody2d = GetComponent<Rigidbody2D>();
	}
	
	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)
            {
				_rigidBody2d.AddForce(new Vector2(0f, 200f));
                _grounded = false;
                _animator.SetBool("Grounded", false);
                _animator.SetTrigger("Jump");
				GetComponent<AudioSource>().PlayOneShot(JumpClip);
            }
	    }

		float move = Input.GetAxis("Horizontal");
		_rigidBody2d.velocity = new Vector2(move * 10, _rigidBody2d.velocity.y);
		_animator.SetFloat("Speed", Mathf.Abs(move));
		
		if(move > 0 && !_facingRight)
			Flip();
		else if(move < 0 && _facingRight)
			Flip();

	}

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

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