using UnityEngine;
public class PlayerController : MonoBehaviour
{
[Header("Movement")]
[SerializeField] private float moveSpeed = 5f;
[Header("Jump")]
[SerializeField] private float jumpForce = 7f;
[SerializeField] private Transform groundCheck;
[SerializeField] private float groundCheckRadius = 0.2f;
[SerializeField] private LayerMask groundLayer;
[SerializeField] private Animator animator;
private Rigidbody2D rb;
private float horizontalInput;
private bool isGrounded;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
animator.SetFloat("Speed", moveSpeed);
animator.SetBool("IsGrounded", isGrounded);
// Input
horizontalInput = Input.GetAxisRaw("Horizontal");
// Ground check
isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);
// Jump
if (Input.GetButtonDown("Jump") && isGrounded)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
}
private void FixedUpdate()
{
rb.velocity = new Vector2(horizontalInput * moveSpeed, rb.velocity.y);
}
private void OnDrawGizmosSelected()
{
if (groundCheck != null)
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(groundCheck.position, groundCheckRadius);
}
}
}