Nerd For Tech
Published in

Nerd For Tech

In just 4 steps, Make a modular moving platform in Unity

The exercise here demonstrates implementing a modular moving platform as a prefab in Unity.

To begin with, it is imperative to setup the camera follow the player object in a platformer project. To do so, it is just a simple drag and drop.

Unity

As soon as the main camera is made to be a child object of the player object, the follow mechanism would be in place.

Moving to the modular moving platform, below are the basic tasks at hand.

  • Deploy two empty objects to get position references for the movement.
  • Write code to move in between these two objects.
  • Check for the player collision to make it move with the platform as long as it stays atop.
  • Once everything in place, make the moving platform a prefab so that it can be used down the line in different ways.
  1. Deploying two empty game objects
Unity

The platform shall move in between these two points.

2. Code for the movement

  • Create a new script and attach it to the platform object.
  • Get a serialized reference to these two empty game objects via inspector.
  • Use the fixed update method over the regular update method to avoid any jittery movement when the player lands on the platform.
  • In the update method, check for the current position of the platform and accordingly divert its route.

Here is a fantastic use of bool to be noted.

C#

3. Checking for the collision to make the player move with the platform.

  • To make the player move with the platform, the same approach of making the camera move with the player in the beginning of this exercise could be used here. Simply making the platform parent of the player object would do the job.
  • Since collision is being checked, another collider needs to be added and the “IsTrigger” needs to be ticked.
Unity
  • The code requires an addition of the OnTriggerEnter method.
C#
  • Also, as soon as the player hops off of this platform, the action above must be reversed.
C#

4. Make it a prefab.

  • Create an empty game object and reset its transform positions.
  • Drag the platform and the target points as children of this empty object. Also, set their transform positions to 0,0,0. (Keep note of the position values to get them back where needed once prefab process gets over.)
  • At last, drag it in the prefabs folder.
  • Reset the transform positions back to the values of choice.

That should be it :)

Here is the final result.

Thank you very much

--

--

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