Wall Jumping in Unity
Wall jumping is a popular game mechanic in platform games and with good reason, it’s challenging and satisfying to reach the top! I’ll quickly show you how to do it in Unity with the use of the Character Controllers built in tools.
In order to wall jump we’re going to need to limit our rules to:
- Must be off the ground
- calculate the surface normal and apply force perpendicular to it.
Sounds difficult? Don’t worry, Unity will do all the heavy lifting!
First we’ll be using a new tool in our arsenal, our players Character Controller!
This looks a lot like OnColliderEnter or OnTriggerEnter doesn’t it? We can work with it!
When we run this code, we’ll see a blue line from whatever objects normal the player will be hitting.
So in order to wall jump, we’re going to need to know we’re on a wall. The easiest way to do it is to select any vertical environment elements and tag them as ‘Wall’.
Currently, our player can change his mind mid jump. In order for Wall jumping to work, we’re going to need him to commit to the jump by only being able to jump when the player is grounded.
Let’s just move the direction and velocity variables down into the .isGrounded part.
Now when the player jumps, there’s no turning back! This will help with our wall jumps. Now let’s get programming! let’s create a boolean for getting permission to walljump.
Now in our controller code, we check to see if we’re not on the ground, and if we’re actually touching a wall, and if that’s true, we’ll set _canWallJump to true.
In order to know the surface normal in order to jump off of which we’ll get off of ‘hit’ from our ControllerCollider, we’ll need a variable holder named _wallNormal.
The next thing we need to think about is if wall jumping is true, when is it false? The first command under Update() where we’re grounded is a good spot.
and where we’re going to wall jump is the else statement where the player normally hits jump a second time.
Here, if the player can double jump, they well, but if we’re touching a wall and _canWallJump is true, then we’ll multiply yVelocity with _jumpHeight. I also multiplied it by .2 for a little extra oomph. Remembering the formula for velocity being direction multiplied by speed, we’ll put _wallNormal (which is direction) multiplied by _speed into our _velocity variable.
That should do it! Let’s see it in action!
visible gizmos aside, I think we have a functioning wall jump! Huzzah! Tomorrow we’ll go over a pushing objects for puzzles!