Objective: Create a functional moving platform.
This tutorial we are going to make a moving platform, a very common element in platformers. To begin, create 3d cube and size it how you want it.
Similar to how we created waypoints in the cinematography tutorial, we are going to duplicate the platform, and rename it point A. Duplicate again and place the platform where you want the platform to move to, and rename this one point B.
Select both point A and point B and remove the mesh renderer, mesh filter, and the collider. This reduces the points to empty objects holding position data. Create and open a a moving platform script.
We need two Transform variables for point A and B, as well as a bool variable. In the update method we want check if the bool is false, then we want to move the platform to towards point B. When the platform reaches point be we want to turn the bool to true.
To have the platform return simply reverse the code with if the bool is true then we move towards point A and when the platform reaches the point we turn the bool again.
Congratulations you have created a moving platform. If you player were to jump on the platform the platform would move out from under the player. If you want the platform to move the player with it then we need to create a way for when the player is on the platform the player is parented to the platform. We can do this by adding a second box collider to the moving platform and raise it above the service slightly and make the on trigger true.
Now set up an on trigger enter method and when the player collides with the moving platform we want to set the parent to the platform.
Now the player will be carried by the platform. If we were to leave the code here then the player will always be parented to the platform meaning when the player jumps off of the platform they will be pushed/pulled by the platform movement. We need to unparent the player using an on trigger exit.
We are practically done however there is one final switch we should make. When the player is being carried by the platform you may have a jagged motion of the player movement. An easy fix is to switch the update method to Fixed Update.
Fixed Update uses the physics update which is a constant update loop used for things that require physics movements.
Now you have a functioning moving platform. You can chance to a vertical moving platform simply by moving point B. Don’t be afraid to experiment with your platforms and I’ll see you in the next tutorial!