Creating a Ladder Climb behavior
2.5D Game Development
Objective: Create a behavior for player to climb the ladder back and forth.
First of all create/add a ladder in your scene and insert a collider component to your ladder which will set motion the climb behavior and make sure that Is Trigger is set to active.
Then create a Trigger function inside the script that is attached to the ladder. In the trigger function, check if the gameobject is player and if true then inside the player script call the Long ladder climb function while providing the enter position.
Enter Pos is an empty gameobject with transform value to shift the player to climb position when climbing.
Now add this function that is being called from the trigger to the player script. This will set a condition for player to choose between climbing ladder and moving around.
Now inside the update of player script, see if the on ladder is true which means that the player is ready to move up, if the player is pressing W key to climb and to down is false which will check if moving up or down. This will disable the condition to be met again for the time being and calls the climb long ladder function while setting the climbing to true.
Inside the climb long ladder function, the climbing animation starts playing and the player position shifts to the enter position as well as the rotation whichever direction the player maybe facing.
Now we check if the player is climbing the ladder and if moving down is false then the controller moves the player upwards until the conditions are set to false.
Now add a cube with its box collider set to trigger which will detect the player and disables the climbing animation and enabling player movement.
Insert this Script to the ladder exit collider which will detect the player upon entry and calls the long ladder exit function while providing the exit location.
This function inside the player script will then stop the climbing animation and moves the player to the platform forward while setting on ladder to false which means the player then can again climb up/down the ladder. The climbing is set to false which means that the condition to player movement is met and it will not go to the vertical movement, instead will go to the normal movement that is to/fro, jump/roll, etc.
Also inside Edit>Project Settings>Physics, turn on the Auto sync Transform to be able to move the player position otherwise the character controller will ignore the transform to this location call.
And this is the final result. Look forward to move down the ladder in the next article.