Platformer: Moving Platform

Introduction

In this article, we are going to talk about how to create a platform that moves back and forth between two points. When the Player jumps on it, the Player doesn’t move with the platform and this will be addressed in a future article.

Waypoint Setup

The waypoints are going to be the two points the moving platform will move between. They are empty objects are named PointA and PointB.

In the MovingPlatform script, which is attached to the moving platform game object, we are going to create two Transform variables to hold the position of PointA and Point B.

Assign the points in the Inspector.

Vector3.MoveTowards

Using the Vector3 method, MoveTowards, which allows us to move the platform towards one of the Points. It requires 3 parameters below…

In the Update, we are setting the position of moving platform to Vector3.MoveTowards passing in the platforms current position, the position of Point B, and the moving speed.

Once the platform reaches PointB’s position it will stop since the current position is the same as the target position. We will now need to move the platform back to PointA and when it reaches PointA, it will need to move towards PointB.

Moving Back-and-Forth

We are going to create an Int variable that will track which point we last stop at.

PointA = waypoint 0

PointB = waypoint 1

At the start, the platform is at PointA so we are moving towards PointB. We are checking if the platform’s position is the same as the PointB’s position then we will change the waypoint value to 1. This moves the platform towards PointA position and when the platform position is the same as PointA’s position, we set waypoint back to 0, which will move the platform back towards PointB.

--

--

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