2.D Platformer: Double Jump!
Today, I implemented the ability to double jump!
Objective
We want to jump when pressing the space key.
Setup
I want the player to jump with out the use of a rigidbody. So I need to create the logic for gravity as well.
With the character controller script in use from Unity, I can use it’s “isGrounded” property to check if the player is touching the ground or not.
Scripting
In the player script, I added some variables.
[SerializeField] private float _gravity = 1.0f;
[SerializeField] private float _jumpHeight = 8f;
[SerializeField] private bool _canDoubleJump = false;
private float _yVelocity;
I want to store the value of the gravity, so when the player jumps, I can have its y position imitate fall.
I also need a jump height, or jump speed, to give the player its height when jumping.
Also, a bool is needed to control the double jump since I don’t want the player to jump infinitely.
And finally, the Y velocity variable will store the value of the sum:
_yVelocity += _jumpHeight;
After a jump, it will also subtract from gravity, making the player fall to the ground.
_yVelocity -= _gravity;
With the fields set, in the Update()
function, I want to check if the player is grounded. If the player is grounded, then we need to check if the jump key has been pressed.
if (_controller.isGrounded)
{
if (Input.GetKeyDown(KeyCode.Space))
{
_yVelocity = _jumpHeight;
_canDoubleJump = true;
}
}
else
{
if (Input.GetKeyDown(KeyCode.Space))
{
if (_canDoubleJump)
{
_yVelocity += _jumpHeight;
}
_canDoubleJump = false;
}
_yVelocity -= _gravity;
}
velocity.y = _yVelocity;
If the jump key has been pressed, we want to store the jump height to the Y velocity variable and set the bool “can double jump” to true.
Else, if the player is not grounded, and if the jump key is pressed, I want to check if the player can double jump.
If the player can double jump, we want to add the Y velocity with the jump height and set the “can double jump” bool to false.
I then need to subtract the Y velocity to gravity and store it into y velocity so I can finally apply the data to the player’s vector3 Y position.
Conclusion
I can now jump and fall through simple logic! Since I am following a course, we are not using a rigidbody to add gravity which would help in that regard instead of coming up with our own gravity system.
That is all for today. Thank you for your time!
Gabriel