In 6 steps, Add a double jump in Unity

Samarth Dhroov
Dec 3, 2021 · 2 min read

The exercise here demonstrates implementing jumping mechanism as part of the customized physics controller in Unity.

The jump task closely resembles to what gravity does in this project. However, the y direction gets a positive value instead of the negative one.

By following these steps, one jump could be written easily.

  1. Create a private variable to keep track of the last y value of the velocity vector.
private float _CacheYVelocity;

2. Create a private variable to add the jump height of choice.

private int _jumpHeight = 50;

3. In the if statement which checks for the player objects’ position on ground, add the following code that captures space input for jump.

if (_characterController.isGrounded == true)
{
if (Input.GetKeyDown(KeyCode.Space))
{
_CacheYVelocity = _jumpHeight;
}
}

So far, one jump seems in place.

To implement double jump, another bool variable is required to know if the player has already jumped once.

4. Create a private variable.

private bool _jumped;

5. In the if statement above, turn this flag to True.

if (_characterController.isGrounded == true)
{
if (Input.GetKeyDown(KeyCode.Space))
{
_jumped = true;
_CacheYVelocity = _jumpHeight;
}

}

6. In the else part where the player gets checked for being in the air, recheck for the space input and add jump height as per choice.

else
{

if (Input.GetKeyDown(KeyCode.Space))
{
if (_jumped == true)
{
_CacheYVelocity += _jumpHeight + 2; // MyConfig
_jumped = false;
}
}


_CacheYVelocity -= _gravity;
}

That should be it :)

Here is the final result.

Thank you very much

Nerd For Tech

From Confusion to Clarification

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Samarth Dhroov

Written by

Work in Progress.

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.