This article will show how to make a moving platform that goes back and forth between two points that you can easily change. We will also set up the Platform to move the Player when standing on it.
The Moving Platform is a cube with the script attached, and the two Points are Empty GameObjects.
In the Moving Platform script, we need to add a few variables, two points to move to, the speed to move at, and a bool to know which point to be moving towards.
In Update, we move the Platform towards Point A at the set speed if the bool is false and towards Point B if the bool is true. Then we check if the Platform has reached either point and change the bool accordingly.
Add the two points to the script.
The Platform now ping pongs between the two points.
If the Player jumps onto the Platform, it still moves but doesn’t move the Player.
To have the Moving Platform detect the Player, we add another Box Collider to it, set it to be a Trigger, and add a Rigidbody.
In the Moving Platform script, 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.
We also need to change Update to FixedUpdate for the Player to move correctly with the Platform.
The Player now moves with the Platform because it is a child, and when the Player jumps off the Platform, it is unparented.
Giving the Moving Platform a parent makes it contained. You can use it multiple times without cluttering the scene.