[Unity] How to Implement Double Jump in 2D Games Using Rigidbody2D

This article introduces how to implement jumping using Rigidbody2D.

You can freely set the number of jumps, making double jumps, triple jumps, and more possible.

Collision Detection

Make sure to set up collision detection for both the stage and the character.

For more details, please refer to this article.

Jump Script

Attach the following script to the character you want to make jump.

The character will jump when you press the space key.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class jump : MonoBehaviour
{
    private Rigidbody2D rigidbody2D;

    public float jumpForce = 200f;

    public int MaxJumpCount = 2;
    private int jumpCount = 0;

    private void Start()
    {
        // Get the Rigidbody2D component
        rigidbody2D = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        // Jump when space key is pressed
        // Allow jumping up to MaxJumpCount times
        if (Input.GetKeyDown(KeyCode.Space) && this.jumpCount < MaxJumpCount)
        {
            this.rigidbody2D.AddForce(transform.up * jumpForce);
            jumpCount++;
        }

    }

    // Reset jumpCount to 0 when landing on the floor
    private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Floor"))
        {
            jumpCount = 0;
        }
    }
}

Setting the Floor Tag

Assign the tag Floor to your floor objects.

You can set this from the Inspector.

Click Add Tag…, then create and select the Floor tag.

Click the + button, type Floor as the name, and add the new tag.

Complete!

You can now perform a double jump!

If the jump force feels too strong and the character flies off-screen, try adjusting the MaxJumpCount value in the Inspector.

Here’s a popular asset for 2D action games.