Implementing a Double Jump - Unity Game Development Tutorial
We're going to start with the project we created in our 'Controlling a Character' Tutorial. For those of you that haven't followed this tutorial, we'll give a quick overview.
We've got our character and a few obstacles for it to interact with.
Attached to the character is the following script.
This script takes input from the player and uses it to move the character accordingly. Currently our character can do a single jump. If the player presses the jump button while the character is on the ground, the Y velocity of the character is increased to make it rise, and gravity is applied to the character to bring it back down to earth.
If you find any of this unfamiliar I suggest working through our tutorial on 'Controlling a Character'
Now let's edit this script to allow the character to be able to do a double jump.
The first thing we’ve done is add a public variable to hold the double jump speed.
We only want the double jump to occur if the player presses the jump button again while the character is jumping, so we've added a private boolean variable to keep track of whether the character is currently jumping. We're setting this to true when the character jumps, and we're setting it to false when the character is on the ground.
We've then added a check to see if the jump button has been pressed again while the character is off the ground and already jumping. If it has, then we add the doubleJumpSpeed to the Y velocity.
We’ll save the script, switch back to Unity and set the double jump speed to 4, which is slightly lower than the original jump speed of 5.
If we play the game now we can press the space bar to make the character jump, and if we press it again we’ll get a double jump.
There’s a problem though. There’s currently no limit to the amount of jumps we can do. If we keep hitting the space bar then the character will eventually jump out of sight.
Let’s make the following changes to the script to fix this.
We’ve added another boolean variable to keep track of whether our character is currently double jumping. We're setting this to true when the double jump starts, and we're setting it to false when the character is on the ground.
Then we have added another check so that the double jump speed isn’t applied if the character is already double jumping.
If we save the script and try this out again, the character is now limited to a double jump no matter how many times the space bar is pressed.
That covers everything for this tutorial. We hope that you found it useful. Please leave any questions or feedback in the comments below, and don't forget to subscribe to get notified when we publish our next post.