How to add double jumping to Unity

How to add double jumping to Unity

Andrew Velez
Posted on 12/23/2018Last Modified: 1/20/2019

The double jump feature is extremely common. You will see it in so many different platformers. In this article I will be going through how to implement double jump in Unity.

Beta Footage of Acorn double jumping in the game Happy Nut.


Below is some code that i implemented in my player class for Jumping. This method is called every frame in the Update Method. The jist of this method is that we are going to apply one initial force when there is an input for jumping. We slowly get rid of that force every frame until we have finished jumping.

 
/// <summary>
/// Handles the key capture for jumping
/// </summary>
private void Jump()
{
    // Start Landing animation a little earlier.
    if (closeToGrounded && MoveDirection.y <= 0)
    {
        animator.SetBool("isLanding", true);
    }
    
    //  We are currently touching the ground or climbing so we can jump.
    var nearGround = Input.GetKeyDown(KeyCode.Space) && (grounded || isClimbing);

    if (isDoubleJumping || nearGround)
    {
        if (!CanJump)
        {
            return;
        }
        // Jump alittle faster than my base walk speed.
        MoveDirection.y = WalkSpeed * 1.05f;

        //Start the animation in Unity. State Machine must have isJumping Parameter.
        animator.SetBool("isJumping", true);

        // We started Double Jumping so we can get rid of the flag.
        isDoubleJumping = false;
    }
    else
    {
        // Move quicker in x direction if were jumping.
        MoveDirection.x = MoveDirection.x * 1.5f;

        // Slowly speed down the player then send him towards the floor until the player is grounded.
        MoveDirection.y -= WalkSpeed / 25;

        if (MoveDirection.y < 0 && grounded)
        {
            MoveDirection.y = 0;
        }
    }
}

To get the method above work you will need to know if you are grounded every frame. I have a class called PhysicsObject that i inherit from with my Player. Inside that class i have a Method called SetGrounded. This method ray-casts downwards on to the ground layer and enemy layer to check if the player has landed on either or is about to land on either.


protected ContactFilter2D contactFilter;
protected RaycastHit2D[] hitBuffer = new RaycastHit2D[16];
protected List<RaycastHit2D> hitBufferList = new List<RaycastHit2D>(16);

void Start()
{
    contactFilter.useTriggers = false;
    contactFilter.SetLayerMask(LayerMask.GetMask(new string[] { "Ground", "Enemy" }));
    contactFilter.useLayerMask = true;
}

/// <summary>
/// Set the variable grounded to true or false.
/// </summary>
protected void SetGrounded()
{
    grounded = false;
    closeToGrounded = false;

    hitBufferList.Clear();
    RaycastDownwards();

    foreach (RaycastHit2D t in hitBufferList)
    {
        if (t.distance < distanceToBeGrounded)
        {
            grounded = true;
        }
        if (t.distance < distanceToBeGrounded * 2.0f)
        {
            closeToGrounded = true;
        }
    }

}

/// <summary>
/// Shoot a raycast downwards to help with determining if something is below us.
/// </summary>
private void RaycastDownwards()
{
    int count = rb2d.Cast(Vector2.down, contactFilter, hitBuffer, shellRadius);
    for (int i = 0; i < count; i++)
    {
        hitBufferList.Add(hitBuffer[i]);
    }
}</pre>

These raycast don't need to be called if the player hasn't moved.



How i setup my jumping state machine in Unity.

Photo of what my state machine in Unity looks like. JumpBegin -> JumpLoop -> JumpEnd. Make sure to get rid of exit time and transition duration if you want the state to transition immediately when a flag is set.



The important part of my state machine is the script on the jump loop state. This Script is what will allow me to Double Jump in my game. The great part about using the Unity State Machine is that it makes it so scripts only work during certain states. It makes sense that the player could only double jump if he is currently jumping. Below will be the last piece of code needed to get the jumping to work.

 
[Tooltip("How many times the player can jump in the air")]
public int NumJumps;
private int currentJump = 1;

override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
    if (currentJump < NumJumps && Input.GetKeyDown(KeyCode.Space))
    {
        currentJump++;
        player.DoubleJump();
    }
}

override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
    if(animator.GetBool("isLanding"))
    {
        currentJump = 1;
    }
}

This code should actually work for more than 2 jumps so if that is something you need than all you need to do is change NumJumps in the Unity Editor.


If You have any questions please feel free to reach out to me. Have a great day!


Andrew Velez
Posted on 12/23/2018Last Modified: 1/20/2019

...

Recomendations

Games for Sale

Comments 0

Display Name

Email


0 / 10