2.5D Platformer: Moving Platforms, Part 2
In this part of the article, I’ll be fixing a small problem with the Player on the platform.
You can see that the Player does not move with the platform, and if I do not move the Player, it will slide off of the platform. To fix this, I’ll have the Player set as a child of the platform when on the platform, then unparent it when jumping off.
First, I’ll add a second box collider to the Moveable_Platform, adjust it up just a little bit, and set it to Is Trigger.
Now in the MovingPlatform script I’ll need to add a check for OnTriggerEnter() and OnTriggerExit(). On the OnTriggerEnter(), I’ll check if the collision is with the Player. If so, I’ll set the player’s parent as the platform. Then in OnTriggerExit(), I’ll check if the object leaving is the player, and if so, I’ll set the player’s parent to null.
Now the Player should stay on the Platform and jump off with no problem.
Now it’s working as it should. As a bonus to this part of the article, I’m also going to show how I modularize the moving platform to be re-used easily.
First, I will create a new empty object named Moving_Platform, and reset its Transform to zero.
Then I’ll move the Moveable_Platform, Target_A, and Target_B into the empty Moving_Platform and change their Transforms to zero.
Now I can drag the Moving_Platform into the Prefabs folder, and I can then add more of them as needed. When I add them into the scene, a designer or I can set where they want Target_A and Target_B to be placed, and the platform will move between them.
You can see above I know have three moving platforms placed, all of which are in different directions.
I hope you enjoyed these articles, and make sure to check back for the next one, where I’ll be setting up a lives counter, and a respawn if the Player falls off of a platform.
As always, I wish you the best of luck on your own coding journey.