Today, I will show you how to make a moving platform for our game. The platform will be moving and x axis.
For our platform to move we need to define point A and point B for our platform to move to. Create two empty GameObject and position them at the position you want your platform move to and from.
Create a new script called MovingPlatform. In the Update() method we need to:
- move our platform to point B,
- if the platform is at the point B, go to point A,
- if the platform is at the point A, go to point B.
To move the platform we will use Vector3.MoveTowards().
Create variables for point A and B, current target and speed. Assign point A and B in the Inspector.
In the FixedUpdate() method we will move the platform, and check if it reaches the current target.
The platform is moving as we wanted it to. But what happens if our player jump on it? The platform is moving but we need to move our player to stay on the platform.
To fix that we will use OnTriggerEnter() and OnTriggerExit(). When our player jumps on the platform we will parent him to it. This way he will stay on it. When he jumps off, we will set the parent to null.
Add a second collider to our platform with isTrigger checked. Rise it so it is above the platform.