Learn Double Jump in Unity
In this article we will add the ability to double jump on our character controller.
Double Jump Script
A new variable to keep track if we already double jumped or not.
private bool _doubleJumped;
When we are on the ground we reset the check if we already double jumped or not.
When we are not grounded we check if the space key is pressed and if we haven’t double jumped yet.
Then we add our jump height to our cached y velocity and set doubleJumped variable to true.
Vector3 direction = new Vector3(Input.GetAxis(“Horizontal”), 0);
Vector3 velocity = direction * _speed;
if (_controller.isGrounded == true)
_doubleJumped = false;
_yVelocity = _jumpHeight;
//check for double jump
if (Input.GetKeyDown(KeyCode.Space) && _doubleJumped == false)
_yVelocity += _jumpHeight;
_doubleJumped = true;
_yVelocity -= _gravity;
} velocity.y = _yVelocity;
_controller.Move(velocity * Time.deltaTime);