using UnityEngine;

public class PlayerController : MonoBehaviour {
    
    public float moveForce = 365f;
    public float maxSpeed = 5f;
    public float jumpForce = 1000f;
    public Transform groundCheck;
    
    private Animator animator;
    private Rigidbody2D rb2d;
    private bool grounded = false;
    private bool jump = false;
    private bool facingRight = true;
    
    void Awake () {
        animator = GetComponent<Animator>();
        rb2d = GetComponent<Rigidbody2D>();
    }
	
	void Update () {
	   grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
       
       animator.SetBool("Grounded", grounded);
       
       if (Input.GetButtonDown("Jump") && grounded) {
           jump = true;
       }
	}
    
    void FixedUpdate() {
        float h = Input.GetAxis("Horizontal");
        
        animator.SetFloat("Speed", Mathf.Abs(h));
        
        if (h * rb2d.velocity.x < maxSpeed) {
            rb2d.AddForce(Vector2.right * h * moveForce, ForceMode2D.Impulse);
        }
        
        if (Mathf.Abs(rb2d.velocity.x) > maxSpeed) {
            rb2d.velocity = new Vector2(Mathf.Sign (rb2d.velocity.x) * maxSpeed, rb2d.velocity.y);
        }
        
        if (h > 0 && !facingRight) {
            Flip ();    
        } else if (h < 0 && facingRight) {
            Flip ();
        }
        
        if (jump) {
            animator.SetTrigger("Jump");
            rb2d.AddForce(new Vector2(0f, jumpForce));
            jump = false;
        }
    }
    
    void Flip() {
        facingRight = !facingRight;
        Vector3 scale = transform.localScale;
        scale.x *= -1;
        transform.localScale = scale;
    }
}
