2.5D Platformer: Character Controller, Part 2
In this second part of my article on creating a Character Controller for the 2.5D Platformer, I’ll be setting up the Gravity, Jumping, and Double-Jumping for the Player.
I’ve already created a variable for gravity and will set it to 1.0f for the moment and adjust it later if needed. To check for gravity, I’ll use a method from the Character Controller called isGrounded to see if the Player is standing on something. If it is true, I’ll do nothing for the moment, and if it is false, I’ll apply gravity.
This now provides gravity so that the Player can fall.
The Player is falling slowly, but I’ll adjust this while adding in jumping as needed.
Now is the time to add jumping for the Player. I’m going to use the Space key to initiate the Player’s jump. First, I’ll check if the Space key has been pressed in the check for the isGrounded.
Now this will still present a problem, as you can see below.
The Player is barely jumping at all. So what happens is that the velocity.y is getting reset to 0 for each frame. To alleviate this, I will create a float named yVelocity to cache the velocity I want to use for y.
Now that I have that code in place, I’ll adjust the values for my gravity and jump height to make the movement a bit smoother.
This gives a much nicer jump, although I think I may adjust the gravity a little bit more, so the Player doesn’t feel like they are being snatched down.
Now I’ll work on the double-jump functionality. First, I will create a bool to determine if the Player can double-jump, and I’ll name it _canDoubleJump, setting its initial value to false. This is because I only want them to double-jump once and only if the Player is not grounded. So when the player first jumps, _canDoubleJump will get set to true. Then if the player jumps again, it will be set back to false. The code for this is shown below.
Now the Player can jump and double-jump.
That completes the setting up of the Character Controller for the 2.5D Platformer game. I hope you found this interesting, and as always, I wish you well on your own coding journey.