Creating a Moving Platform in Unity

Objective: Create a new platform with the ability to move between defined points.

First step was to create a new prefab based on the regular platform but I also created a new script called moving platform and attached it to the platform.

In the scene I create some empty objects as a child of the moving platform. We are going to use these objects as the points that the platform has to follow while it is moving.

In the moving platform script I declared some variables. One for the speed of the platform, another for the current target and an array to save to different positions the platform has to move.

In the start method I create an array of transforms to save all transforms of the child objects of the moving platform. Then I create a list of Vector3 and through a foreach loop I add each position to the list. Finally I just cast the list of positions to an array and save it in the waypoints array. This array is going to be used to change the target of the platform during the game.

In the FIxedUpdate method I check if the platform has more than one waypoint to start the movement. Then I assign the current target and move the platform using the function MoveTowards passing as a parameter the current position and the current target.

Then if the current position is equal to the current target I check if the currentTarget is the last waypoint. I set the current target as 0 to go to the first point. In other cases I just increase the current target to go to the next waypoint.

And that’s it!! We have the moving platform for our level.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rusben Guzman

Rusben Guzman

A Software Engineer passionate about game dev and interactive products with Unity. I consider video games to be the artistic expression of programming.