Nerd For Tech
Published in

Nerd For Tech

Moving Platform — Refactor

This article will expand on the Moving Platform from a previous article. We will add the ability to use any number of waypoints and the option to go back in reverse on the waypoints or start again from the beginning.

The Platform has a Box Collider set to be a Trigger with a Rigidbody to detect the Player stepping on and off the Platform. The Waypoints are empty GameObjects.

To change the MovingPlatform script to use any number of Waypoints and decide how it behaves when reaching the last Point, we need some variables.

  1. An Array to hold the Waypoint Transforms.
  2. The index for the current Waypoint in the Array.
  3. The speed at which the Platform will move between Waypoints.
  4. If the Platform should go straight to the first Waypoint when it reaches the end or reverses through the Array.
  5. If the Platform is currently going in reverse through the Array.
  6. If the Platform is at the current Waypoint index position and should change the index.

This method checks if the Platform is at the position of the current Waypoint and sets the at Waypoint bool to true if it is.

This method checks if the Platform is at the Waypoint, we then change the current Waypoint index value. If the current Waypoint is the last in the Array, we check if the Platform should reverse at the end and set in reverse to true and decrement the current Waypoint. If not, then the current Waypoint is set to the first Waypoint, and at Waypoint is set to false.

For the other Waypoints, we decrement the index if in reverse and set in reverse to false when the first Waypoint is reached. If the Platform is not in reverse, we increment the index, make sure it does not exceed the Array index range and set at Waypoint to false.

This method gets the Waypoint position and then moves the Platform towards it at the set speed multiplied by the time since the last frame.

We are using FixedUpdate for the movement of the Platform so that it will move the Player smoothly. The first thing is to make sure there is more than one Waypoint in the Array. Then we check the Platform’s position, get the next Waypoint, and then move the Platform to the current Waypoint.

Finally, we add an OnTriggerEnter that checks for the Player and then sets the Player to be a child of the Platform and add an OnTriggerExit that removes the Player’s parent.

The Platform now loops through any number of given Waypoints.

--

--

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