How to add moving platforms in Unity

Let’s go over how to add moving platforms to the platformer project.

First, create a cube that will be used for the platform. Create an empty game object and add the cube as a child of this object:

Duplicate the platform twice and rename the new objects to Waypoint_A and Waypoint_B. Remove all components from the duplicates. The duplicate objects will be used to set the waypoints for the platform:

Leave Waypoint_A at the exact same position as the platform and then move Waypoint_B to the position where the platform should go to:

Create a script called MovingPlatform and add to the platform object:

Select the platform and add an additional Box collider and enable IsTrigger. Move the collider slightly up. This collider will be used to detect if the player stands on the platform:

Open up the MovingPlatform script. Add a serialized transform array for the waypoints and a serialized float for the speed of the platform. Also add a Vector3 for the current target the platform should move to:

In the Start function set the target to the second waypoint in the array:

When handling objects in Unity that are affected by physics, it is best practise to use FixedUpdate instead of Update to avoid jitter. FixedUpdate has consistent frames instead of variable frames as in Update. Check if the platform is at the same position as the target, and if not move the platform towards the target. When target has been reached, set the target to be the other waypoint:

The player will not move with the platform automatically when standing on it. For the player object to move with the platform it has be parented to it. Add an OnTriggerEnter and an OnTriggereExit function to handle the parenting:

Final result:

Good luck!

Unity / C# Game developer