Now that we have our player character moving from left to right, we need to take a step forward and make him jump.
We need to create a new binding into our
PlayerInputController, this binding will be our Jump binding!
We'll be creating more bindings throughout this tutorial.
And we need to create a new binding for the keyboard too.
Once created, don't forget to "Save Asset", otherwise the binding will not be created.
speed we will need a new property to tell us the jump force for our character.
Update(), we need to tell that the Y velocity for our character body.
Our character can jump! YAY! But he can jump and jump and jump as long we keep pressing the Jump button and we don't want that.
To fix that, we need to know if our character is touching the ground before jumping.
Let's add a new game object as a child of our character. This will be our "ground checker".
Once created, move it slightly down in the Y axis, -0.55 should be enough.
Couple more things we need to add to our code:
- Property telling if the player is grounded or not.
- A game object property so the code knows what is our ground check object.
LayerMaskso our code knows what is a ground in our game.
Let's add them!
In the editor we're going to drag and drop the
GroundCheck game object into our
groundCheck property in the player controller script.
For the layer mask, we'll need to do some extra work.
Go into the inspector (can be the player object) and select Layers, and
In this new screen, create a new layer called
We have our Layer now, let's change our ground game object layer to be ground.
And with that, go back to our player input controller, and change the
We have everything we need in order to make our player jump properly!
Physics2D class from Unity, we'll check if our
groundCheck is overlapping with something, in this case the ground!
Run the game and keep pressing the jump button, we won't be able to jump more than once!
It's not good to handle physics (like moving the
rigidbody around) in the Update method, so we'll move some of the code to the
FixedUpdate() code, and leave the
Update() method to handle the player input.
Some extra properties:
And the actual code:
Thanks for reading! Hope this series is being helpful and fun for you as fun is being writing them! See you in the next chapter!