using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float speed = 5;
private Rigidbody2D body;
private Animator anim;
private bool grounded;
private void Awake()
{
//Grab references for Rigidbody and animator from object
body = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
private void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);
//flip player left and right
if(horizontalInput > 0.01f)
{
transform.localScale = Vector3.one;
}
else if (horizontalInput < -0.01f)
{
transform.localScale = new Vector3(-1, 1, 1);
}
//jump statement
if (Input.GetKey(KeyCode.Space) || Input.GetKey(KeyCode.W))
{
if (grounded == true)
{
Jump();
}
}
//set animator parameter
anim.SetBool("Run", horizontalInput != 0);
anim.SetBool("Grounded", grounded);
}
//jump method
private void Jump()
{
body.velocity = new Vector2(body.velocity.x, speed);
grounded = false;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground")
grounded = true;
}
}