Daily Progress: Jumping!

Objective: Create a function for jumping.

This tutorial is all about adding the ability for our player to jump. To spice this up from our normal methods, I’m going to not use a jumping variable. Instead We will be using a return method and a coroutine.

To begin we have a rigidbody 2D on our player and we need to create a handle for this.

Create a Movement method where we control the player’s movement with horizontal input and the rigidbody. Use a Vector2 with the local variable tied to the horizontal input multiplied by a variable for speed. My speed is set to 3.0f.

Call this method through the update method.

Now your player will move with the A and D key’s or the arrow keys.

Great, now we can move on to jumping! We need a float for our jump height and a bool to reset the jump ability.

We need to create a layer! On my project I selected the floor objects that contains all the walkable objects. In the inspector you have a drop down option for layers. Select add layer and the first layer you can add is on layer 8. I named mine “Ground”

Now we have all the information we need to set up our bool return method. We are going to 2D raycast. the physics raycast needs an origin, and direction, a distance, and I’m using a layer mask. This way the ray will ignore our players collider and only respond to the layer “Ground”

What do we do with this? well, if the hit info local variable’s collider is not null, meaning it is in contact with the ground layer we will use another if statement for if the reset jump variable is equal to false then the return bool will return true. Else the return method will return false.

Back to the movement method, if the player presses the space key and is grounded returns true, then we need to add our jump height to the player’s rigidbody’s y axis. We also want to call a coroutine. the coroutine we are creating next.

Moving on to coroutine mentioned before. We are going to use this coroutine to set the reset jump to true, waif 0.1 seconds and set the reset jump back to false.

Now when we jump, the reset jump is set to true, meaning is grounded returns a false, so our player cannot jump again until the raycast comes in contact with the layer mask again. We have restricted our player to only 1 jump. Don’t be afraid to experiment with you jump height and I’ll see you in the next tutorial!