c# – Allow Player to Jump Only when on Ground Unity


I try to let the player to jump when only it is on ground but it keeps jumping even it was in the air

here is the code :

public class Player : MonoBehaviour
{
    float moveSpeed = 5;
    public Rigidbody2D rb;
    float jump = 5f;
    bool isGrounded;
    // Start is called before the first frame update
    void Start()
    {
        rb.GetComponent<Rigidbody2D>();
    }
 void Update()
 {
     isGrounded = Physics2D.Raycast(transform.position, Vector2.down, 0.1f);

     float moveHorizontal = Input.GetAxis("Horizontal");
     rb.velocity = new Vector2(moveHorizontal * moveSpeed, rb.velocity.y);

     if (isGrounded && Input.GetButtonDown("Jump"))
     {
         rb.AddForce(Vector2.up * jump, ForceMode2D.Impulse);
     }
 }

Leave a Reply

Your email address will not be published. Required fields are marked *