Creating a Moving Platform
It is time to create moving platforms for the 2.5D game. Let's start by creating a green material to identify the moving platforms.
Creating the Moving Platforms
Now we are going to duplicate the moving platform two times to create a starting point and endpoint for the platform to move between. These duplicates will be put at the starting point and endpoint of the platform's path and will have all components deleted to make them empty objects.
Create a new script and for the moving platform and add it to the moving platform.
Create some variables to hold the transforms for the starting point and endpoint and the platform's speed.
You will also create a boolean variable to determine if the platform needs to change directions.
Now we are going to create a class that will hold the logic for the moving platform. The logic will be if the platform is at the starting position it will not need to change directions and will move to the endpoint. If the platform is at the endpoint the direction will need to change and the platform will move to the starting point.
You will call this class in a fixed update.
Add the starting and endpoints to the script in the inspector and the platform will be moving.
Getting the Player Moving with the Platform
This is good, but the player will not move with the platform, which is expected for this mechanic.
To fix this create another box collider on your moving platform and offset it by 0.3 on the y axis. This collider will also be marked as a trigger.
In the moving platform script, you will use OnTriggerEnter to parent the player to the platform when it lands on the platform. You will then use the OnTriggerExit to unparent the player when they leave the platform.
This will get the player moving with the platform.
Modularize the Moving Platforms
To modularize this system you can create an empty game object and zero out its position.
Now add the moving platform and the starting and endpoints to the empty game object and zero out their positions.
Now you can create a prefab out of this.
This will allow you to add in the prefab. Move it to the starting position of the platform, and then move the endpoint to where you want it to end. This will make it fast and easy to create multiple moving platforms.