Menu
CoddyTech

Moving Platforms

Part of the Building Real Games section of Coddy's Unity journey. Lesson 49 of 56.

challenge icon

Challenge

Medium

The blue platform should glide back and forth over the gap. Keep everything from the last lesson.

Fill in MovingPlatform:

  • Two fields the Inspector sets, distance (3) and speed (1.5), and a public Vector3 delta.
  • It glides from where it starts to distance units along +x at speed units per second, then back to its start, and so on for ever.
  • Every frame, delta is how far it moved in that frame: its position after the move minus its position before.

A CharacterController is not carried by what it stands on: on a moving platform it stays where it is, and the platform slides away under it. Moving its transform.position along does not work either: the controller's next Move starts from where the physics last saw it, and undoes the change. Make Player ride along:

  • Add OnControllerColliderHit. When the hit's normal points up (hit.normal.y above 0.5: the player stands on it) and the object has a MovingPlatform, keep that platform in a field.
  • In Update, add that platform's delta to the motion passed to controller.Move, then forget the platform (set the field to null). The Move call finds it again for as long as the player stands on it.

Press Play, jump onto the platform and ride it, then Check.

Try it yourself

using UnityEngine;

public class MovingPlatform : MonoBehaviour
{
    // A later lesson fills this in: a platform that glides back and forth.
}

All lessons in Building Real Games