Making Moving Platforms In A Unity Platformer

Today I am making some of the 2D platforms in my game move between defined points.

Today’s Objective: Write modular code to make a platform object move automatically between 2 or more waypoints.

Note: I am making a 2.5D platformer, so all the objects are 3D. However, the code and design should work with 2D as well, as long as you switch to the 2D equivalent Unity components (RigidBody/RigidBody2D, etc.).

Scene Setup:

First create or select the platform which will move. It needs a non-trigger Collider to act as the physical form, and another trigger Collider to act as the detection for objects that are on top of it.

The trigger collider should be offset to be above the platform while not touching the platform (as this can make it detect collisions with itself).

Also, the moving platform (OR every object that could land on it and should move with it) needs a RigidBody component to allow trigger detection.

Turn off gravity, and lock position/rotation as needed

The Code:

Create a new script called something like “MovingPlatform”. First I define the variables I will need:

Next, the functions involved:

Inside FixedUpdate (because it’s physics), there is a bit to write, so I’ll break it into smaller segments:

Hope you got all that.

Next is the wait-at-waypoint functionality, as well as the detect-objects-on-top-of-platform functionality.

Finally, an optional extra:

For modular, reusable components like this, especially waypoint systems, I like to show the waypoints in the Editor’s scene view for easy understanding. You can do this by adding the OnDrawGizmos method like so:

That creates the following:

And is much easier to quickly interpret than:

I hope this was useful to you! :)

--

--

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
Vincent Taylor

Vincent Taylor

Unity game developer / C# Programmer / Gamer. Australian (Tasmanian) indie games developer for 10+ years. Currently looking for games industry employment.