How To Prevent Multiple Jumps In 2D C# Game

Hey,
I’ve created a 2D game with basic movement. The jump function works, but allows for infinite jumping. What’re some simple ways I can use to make sure the player is grounded before allowing them to jump? Do you have any other solutions? I’ve tried to follow a few tutorials, but they didn’t work too well. Thanks.

using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
    private float moveSpeed = 5f;
    private float jumpHeight = 300f;
    private Rigidbody2D rigidBody;
    // Use this for initialization
    void Start()
    {
        rigidBody = GetComponent<Rigidbody2D>();
    }
    // Update is called once per frame
    void Update()
    {
        if (Input.GetAxisRaw("Horizontal") > 0.5f || Input.GetAxisRaw("Horizontal") < -0.5f)
        {
            transform.Translate(new Vector3(Input.GetAxisRaw("Horizontal") * moveSpeed * Time.deltaTime, 0f, 0f));
        }
        if (Input.GetKeyDown(KeyCode.W))
        {
            rigidBody.AddForce(new Vector2(0, jumpHeight));
        }
    }
}

You need to make sure the player is grounded.
There different ways of doing so, one could be to check if the player is colliding with something underneath him and if so, allow the jump.
Another way could be to cast a 2d raycast down and check if the distance to the closest collider is 0 (or a really small value).
Once you find the most suitable way of checking it, just apply that value to a bool called “isGrounded” and change the

if (Input.GetKeyDown(KeyCode.W))
{
    rigidBody.AddForce(new Vector2(0, jumpHeight));
}

To

if (Input.GetKeyDown(KeyCode.W) && isGrounded)
{
    rigidBody.AddForce(new Vector2(0, jumpHeight));
}
1 Like

I show not one but three (count 'em!) different ways of animating a 2D character with limited multiple jumps (my demo allows exactly one, but zero would be even easier) in this article.

HTH,

  • Joe

Previous answers give you idea on how to check if player is grounded. To prevent double jumping you should use the state machine, or you’ll face consequences described here soon.