Unity Development — Double Jump
While it wasn’t the standard when video games first became extremely popular in the 80’s, now almost every game with a jump is expected to have a double jump. Sometimes they have to be unlocked later, but nonetheless, show up eventually. Here’s how we can code one in ourselves.
In order to learn the double jump, we must first be able to jump. You can use whatever technique you feel comfortable using. For this example, we are going to use a Character Controller in a 3D game setting.
First, create your Player as a Capsule, Cube, or any object you like. Then, add a Character Controller component on to them.
Attached a script to the Player and let’s dive into the code. We’ll need a reference to the Character Controller. Declare it at the top and set the reference in the Start() method.
Character Controllers have a ‘Move’ function, which moves the object based on a Vector3, time, and speed. Very similar to Trnsform.Translate. The initial setup with horizontal movement looks something like this.
The Character Controller has a function to check if the object is grounded. We are going to use this for our initial jump. If the player is grounded and the spacebar is pressed, then they will jump. In this case, the jump is going up on the Y-axis and it will be placed on a separate variable so when the Update() method goes to the next frame, it is not zeroed out again.
‘JumpHeight’ and ‘gravity’ are variables that you can change to any float amount to see how you want your game feel. Either way, this is saying that a the y-axis will go up based on a button press when Grounded, otherwise gravity will take over in the air. We also need to set up the Character Controller Y-axis based on the separate yVelocity variable we discussed at the end of Update().
Finally, it is time to get to the double jump. We only want a double jump, not a triple or infinite jump. With this in mind, we need a way to tell whether or not we have already jumped in the air or not. The simple answer is to use a boolean. The boolean of canDoubleJump will be true once in the air, but false after the second jump. The code will look like this.
There you have it. You can set up levels in your game with REALLy high platforms, because your players can now have the gift of the double jump.