A Physics Based Character Controller for Unity — Part 2 Jumping

Andrea Zilio
3 min readJul 12, 2021

--

What would a platform player be without… yes right jumps.

Let’s add those to our 2.5D platform game, a single and a double jump will be nice features.

Single and double jump implemented

Creating the variables in the player script

So far we simple used a var velocity defined by the direction and speed, but as its y value gets reset each time the update method runs, we are going to add an additional variable to cache y value of velocity: _yVelocity.

The double jump should happen only once, and only if the player is in the air. To track this we create another boolean variable.

private float _yVelocity;
private float _jumpHeight = 25.0f;
private bool _jumpAgain = false;

Implementing the single jump

From the last article we already have an if else statement checking whether the player isGrounded or not. Here is what it looks like

if(_controller.isGrounded == true){
//do nothing for now
}
else{
velocity.y -= _gravity;
}

Feature: — When the space bar is pressed, the player jumps once. He can only do this when he is on the ground.

Instead of doing nothing, we pass the _velocity the value of _jumpHeight when the space key is pressed. We also change velocity.y to _yVelocity in the else statement and pass the value of _yVelocity to velocity.y at the end.

If you are wondering why there is a solution for Unity 2020. If you are using 2019 you can simply write:

_yVelocity -= _gravity

with 2020 however it no longer works and /3 will fix it.

Implementing the double jump

Feature: — When the player has jumped once and the space bar is pressed, he will jump again — and thereby double jump. The player can only double jump once after each single jump.

Our boolean _jumpAgain tracks whether or not the player has jumped. Its default is set to false. Once the player has jumped once, it will be set to true.

No the player is in the air, thus the else statement applies. When the space bar is pressed and the _jumpAgain bool is true, then we can add another _jumpHeight to our yVeolocity. To prevent any further jumps for this round we set the _jumpAgain to false.

And that’s it for now. We can now move and jump. It is time to make that game environment a bit more interesting by creating collectables and moving platforms in the next article.

--

--

Andrea Zilio

Passionate Game Developer and Learning Expert. I love to create games and interactive experiences using Unity, Articulate, C#, JavaScript, PHP, HTML, CSS.