Moving platforms usually are the first obstacle of player when played the platformer game first time, especially for those who are not good at action game. Yet, it is a common level design in this type of game.
In this article, we will create a simple direction moving platform.
Basic moving function
First let’s create 2 target position in game scene. Duplicate the moving platform twice, and rename the new gameobjects to Point_A & Point_B. Then remove all the components within except transform. We will just use their position as moving target.
Then create a new script and attach it to Moving_Platform. First we will create the function of moving.
Create 2 transform variables of point A & B, then use Vector3.MoveTowards in Update() and set point_B as the first target.
This is the basic to move platform. However, we need it to move between 2 points. We have to set the turning point to the moving method.
I will use switch statement as a two-way switch to change the moving direction.
Create a new integer variable as switch ID and a new transform to set the next target, and use this ID in switch statement.
Then we need to set the target in MoveTowards method to _selectedTarget.
And we can create an if statement to switch the ID when platform is reached one of the target position.
All done! Back to editor and drag in point A & B into attached script and it should work!
Untouchable platform issue
Once you played, you might notice that Player could not stand on platform. It will just slipped away like this:
To fixed this issue, we need to make Player become the child of platform when standing on it.
Add a rigidbody and a box collider with setting as trigger. Adjust the trigger box collider slightly higher than platform.
Inside script, add two methods: OnTriggerEnter() & OnTriggerExit().
With these two detection, Player should be able to stand on platform now.
Extra: modular moving platform system
Once we finished the moving platform, we can create an empty object to store the platform and 2 target points as modular. And also drag the whole bundle into Project as a new prefab.
Now if we want to add a new moving platform in scene, simply drag it in from prefab and move the Point_B as target position.