Watch your step, they move on their own.
Time to add in some challenges while we travel through the level, time to add in some moving platforms!
This is what we are aiming for in this article, being able to jump on a platform and moving along with it.
First, we want to set up the moving platform. Here we can get a cube stretch it out and add a new script to it, calling it moving platform. We also need a rigid body with gravity turned off as it will be needed later to get the player moving with the platform.
Now to open up that Moving Platform script. Here we want to travel between 2 different positions, which means we will need somewhere to store those values. We can also add a speed at which we want them to travel and a bool for if they are going forwards or back.
In update, we can check if we are moving forward and if we are we can use the MoveTo function to move between our current position and the waypoint. We should also check if we have made it to the waypoint and if we have change forwards to false.
Using 2 empties to hold the transform for the waypoints and dragging them into the moving platform script should give us a working platform.
Now we have the platform moving but the player doesn’t move with the platform?
This is an easy fix, all we need to do is parent the player to the platform. Here we can add another box collider to the platform and move it slightly up so when the player lands on it we can use on trigger enter to parent them to the platform.
Back in the Moving Platform script, we can add an on trigger enter and an on trigger exit, since we don’t want the player moving while they aren’t on the platform.
Looks like the parenting is happening but the player isn’t staying on the platform??
This is because of the update method we are trying to use, if we change it to a FixedUpdate it will fix this problem. All physics is done in the fixed update and since the Character Controller is a physics-based controller it makes sense that it would need the FixedUpdate to stay with the platform.
And there we have it! we might have had a couple of little mishaps along the way but we got there in the end!
We can use this method to be able to make elevators as well, we just need to change where the waypoints are. But with that, we are done here! So, see you in the next one!!!