Platformer: Modular Moving Platform

Introduction

In this article, we are going to cover how to create an easily adaptable moving platform, where the game designer just needs to assign the waypoints they want the moving platform to move through in sequential order.

Variables

We are going to declare an empty array of Transforms that will hold the different points the moving platform will move between. Make sure to serialize it, so we can assign the points in the Inspector. Another variable is an Int variable that will keep track of which number waypoint the moving platform is moving towards.

The Inspector

Currently, there are three waypoints: 0, 1 and 2.

We are going to assign them to the waypoints array and the platform is going to move in the sequential order of the elements (Element 0, Element 1, Element 2).

The Code

In the Update, we are setting the transform of the platform to move towards the waypoint in the array that is determined by the targetID. The waypoint beginning position is at waypoint 0, which is Element 0 in the array. At the start, we want the targetID to be the waypoint in Element 1.

So, we will set the targetID to the declared targetID, which is 0, plus 1 (meaning it is now 1) divided by the length of waypoints array (3) and returning the remainder. Lets break that down.

0 = (0 + 1) % 3

1 % 3 so the remainder of 1 / 3 is 1.

This is all resulting in the targetID being 1 on the Start.

This line of code seems redundant, but will prove usual in the Update.

As the platform is move toward the waypoint determined by the targetID, we check to see if the platform’s current position is the same position of that target waypoint. If it is we will then use that same line of code from the Start, which will increment the targetID and if it gets to the last waypoint it will reset itself back to the first waypoint.

Examples

In the Inspector, you can see how the TargetID corresponds with the waypoint in the matching Element number. When gets to the last Element, it resets back to 0.

This shows when we add another way, it again goes in the Element number order and when it gets to the last Element, it starts back at the beginning.

Prefab

Lets make a prefab of this. Create an empty game object and zero it out.

Don’t forget to zero out the moving platform and waypoints before making it a prefab. This allows a game designer a blank slate and they can adjust the waypoint; add more or remove some. This is the beauty of making it modular.

Cheers everyone!