Nerd For Tech
Published in

Nerd For Tech

Creating a Moving Platform

Objective: Create a platform that moves between two points.

We’ll begin by giving our platform an additional Collider. This one will be used only to detect when the player is standing on the platform, and will have its Is Trigger property checked. It will be offset vertically a bit.

We’ll also create two empty Game Objects that will have only Transform components. These will be the points the platform will move between. They’ll be invisible in-game, but we’ll give them gray icons so we can see them in the Scene view.

Now we’ll create the script. We’ll assign our empty Game Objects to _pointA and _pointB. In the Start method, we’ll assign _pointB as our first target. (Since we’ll have the platform start at the same position as _pointA, B bill be our first target.)

Next, we’ll work in the FixedUpdate method. This method can be used for physics to keep things from getting “jittery.” First, the platform will move from its current position towards the target position. Next, it will check if the distance from its current position to the target position is less than a very small number. If it is, we have arrived at our target. If the target was point A, the new target will be point B, and vice versa.

Now we’ll look for our player. If the player touches the trigger collider, the player will become a child of our platform, moving with it. As soon as the player leaves (exits) the collider, the player’s parent is set to null, freeing it from being moved by the platform.

Note that although we have the platform moving horizontally in this example, the points can be placed anywhere and the platform will move in a straight line between them.

--

--

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