Objective: Implement gravity and the ability to jump!
In the last tutorial we set up a physics based character controller with horizontal input, direction and velocity. For this platformer we need to create a jump function.
Following directly after the last tutorial, open the player script and we will need to check if the player is on the ground or not. We can do this using a build in “isGrounded”.
We want to set up an input for when the player is grounded, to initiate a jump.
When we hit the space key you are altering the Y axis by a float amount. For me, the float “_jumpheight” is set to 15.
With the current set up with our update method we are setting the Y axis to zero every frame. One way to counter this is to cache the Y axis.
With the Y axis cached we can add to with the input.
Now when the space key is hit the player will jump up, however, we have nothing weighing the player down. Gravity. We need to define gravity.
When your player is not grounded they gravity needs to weight them back down. So you will want to subtract the Y axis with your gravity variable.
Your player will now jump, and return back to down!
Now that we have the ability to jump, Let’s create a double jump. To do this we will need to create a bool.
We need to use this bool to control when/if we can double jump. After we jump we want to set the bool to true. In the else section of the is grounded check, create another input function using the space key and the parameter of the bool being true.
Now, when we hit the space key after we jump and before we hit the ground the bool will change back to false, meaning we will only be able to jump one extra time. To have the player jump after pressing space the second time we need to add the jump height to the Y axis again.
Now, your player player can jump, and even double jump. Feel free to change the values to better suit you needs, Lower the gravity or raise the jump height. I’ll see you in the next tutorial!