Scripting the Player (Part 3)
Creating the Double Jump
Now that our player can jump and fall at a reasonable pace, we can add a new function called double jump. The logic behind the double jump is very simple and follows the same principle as the regular jump.
Understanding the logic:
In our current script, we have our player jump when we press the space bar then our player falls due to the set gravity. What we want is to basically have the double jump happen before the gravity happens but after we have triggered the initial jump. To accomplish this, we will need to set up a Boolean to check whenever our player is in the air and has started the initial jump. Then and only then, do we allow the player to press the space bar again to have our current Y position be added by another jump variable. Then we set the Boolean for the double jump to false so the player can only do the double jump ONCE per grounded jump.
Scripting the Double Jump:
To start the double jump, I first created another handle for the second jump multiplier. I called this variable “double jump”. I didn’t want to alter the basic jump variable.
Second, I created a Boolean variable which I set the default to “false”. Then I enable the Boolean when the “isGrounded” initial jump is activated.
In the else statement, I use another IF statement to check if another space key was pressed, and if the double Jump was set to true. If those two conditions are met, the player is able to initiate the double jump. I take the yVelocity which houses the current Y position and add in the double jump variable. At the same time, I also set the double jump Boolean back to “false” to limit the double jump to only one time.
If that set, we should be able to create an clean and tight double jump system, if the player is jumping too much, we can adjust the variables within the inspector.