Wall Jumping in Unity
This article will show how to add Wall Jumping ability to the Player from a previous article. The wall jumping will allow the Player to between two walls to reach a new area.
The easiest way to detect a surface that the Player can use for wall jumping is by giving them a Tag.
In the Player script, we need to add two variables and change the two local variables in Update to be global.
- A bool to know if we can execute a wall jump.
- Gobal Vector 3 variables for direction and velocity.
- A Vector 3 to store the normal direction of the wall that the Player hit.
To get more consistent gravity, we can move it to FixedUpdate.
The Character Controller component comes with methods like OnControllerColliderHit. This method is called anytime the Controller collides with another Collider and returns information about the hit object. If the Player is not on the ground and the hit object is tagged as a Wall, we store the hit wall’s normal direction and allow the Player to perform a wall jump.
In Update, if the Player is on the ground, we set it to not wall jump. If the Player is not on the ground, presses the space key, and can wall jump, we push them off of the wall by changing the velocity to the hit wall’s normal multiplied by speed. Then to move the Player up, we set the y axis velocity to the jump height and set the can wall jump to false.
In Play Mode, the Player can now wall jump to the next level.