Nerd For Tech
Published in

Nerd For Tech

In 6 steps, Add a double jump in Unity

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.

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