It is time to make our Platform Game a little challenging: getting a platform moving! It is actually pretty simple. If you remember, we can use Vector3.MoveTowards function to change the position of a game object from a point to a desired target point.
First, we need to declare the points that we want our platform to go in between. Just duplicate your platform and drag the duplicated platform to the desired end of the move location; remove all of the components except the Transform — we only need it. Repeat the process for the beginning point of the Platform, and name them accordingly.
Now, we are ready to code. Create a new script for the Moving platform. In order to make sure that the platform will reach to the desired points, we need to assign a bool for the return; so that we will change the direction of the platform at these points.
However, you will realize that our character will slip down from the Moving Platform.
As can be guessed easily, this is a result that occures from the two objects are handled seperately. In order to make them share the movement of the platform, we need to make the Player child of it as long as it is on it.
We already have a box collider (hard surface) on the platform. But, we can add more colliders to it if we want to. Add a box collider as a trigger to the moving platform and increase it’s height so that we will be sure that it will we triggered as player touches it.
Now, all is left is to set the moving platform as a parent object to the player once they are collided and deattached them once the Player leaves it.
A quick reminder; changing the Update method to FixedUpdate was recommended in order to solve the stuttering problem while on the moving platform. I have actually gone nuts at first since my player was again sliding off the platform despite being parented to it. Changing the Update to FixedUpdate also solved this.
Since we have hard surface collisions with the platforms, it is better to freeze the rotation on all of the axis to prevent our character from acting weirdly if it collides with a corner etc.
And that’s all :)