How to set up a ladder system for platformer in Unity
Let’s go over how to add ladders to the platformer project.
I will continue to add to the player script from this article. Once again, I used animations from mixamo.com.
Create the ladder object and add three game objects: one for detecting when the player is at the top of the ladder, one for when the player is at the bottom and the last one for the player position after climbing on top (this is similar to how we handled the climb up function from the ledge grab system):
Open up the player script and add three public functions. One for grabbing the ladder, one for when the player is on top of the ladder and the last for climbing off the ladder at the bottom:
Inside the PlayerMovement function limit the player movement to vertical only and set the climbing animation speed to match the speed of the movement:
Create three scripts: one for the ladder, one for the top collider and one for the bottom collider:
Open up the Ladder script. Add four serialized variables:
- the rotation of the player when grabbing the ladder,
- the position of the player after climbing up the ladder,
- a reference to the top of the ladder game object,
- the rotation of the player after climbing up the ladder.
If the collider has the tag “Ledge”. activate the top of the ladder game object and call the GrabLadder function on the player:
Open up the TopOfLadder script. When colliding with the player, trigger the atTop animation, disable the Character Controller and deactivate this object to ensure the player does not collide with it if it is not on the ladder:
Open up the BottomOfLadder script. If the player is colliding with the object and if the the down arrow key is pressed down, call the ClimbDownLadder function:
Open up the Animator window for the player. Add a bool for checking if the player is grabbing the ladder. Also add two triggers for climbing off the ladder (top and bottom) and lastly the climb speed:
Add the animations to the Animator and transitions:
On the Climbing Ladder animation enable the parameter for the climbSpeed to ensure the animation speed is controlled by the script:
On the Climb To Top animation add a new behaviour script:
Open up the behaviour script, and on the exit call the SetTopOfLadderPosition function on the player:
Lastly, select the ladder and set the serialized variables:
Good luck!