Menu
CoddyTech

Ride the Platform

Part of the Building Real Games section of Coddy's Unity journey. Lesson 51 of 60.

A CharacterController is not carried by what it stands on: on a moving platform it stays put, and the platform slides away under it. Moving its transform.position does not help, because the next Move starts from where the physics last saw it and undoes the change.

So the player adds the platform's move to its own. OnControllerColliderHit(ControllerColliderHit hit) runs for each collider a Move touches; a hit from below has hit.normal.y near 1. A ferry that carries a crate the same way:

private Ferry ferry;

void OnControllerColliderHit(ControllerColliderHit hit)
{
    if (hit.normal.y > 0.7f && hit.gameObject.TryGetComponent(out Ferry f))
    {
        ferry = f;
    }
}
challenge icon

Challenge

Medium

Make the player ride the moving platform.

  1. In Player, add private MovingPlatform platform; and OnControllerColliderHit: when hit.normal.y > 0.5f and the object has a MovingPlatform, keep it in platform.
  2. In Update(), put (move + velocity) * Time.deltaTime in Vector3 motion. If platform != null, add platform.delta and set platform = null.
  3. Call controller.Move(motion).

Press Play and jump onto the platform: it carries you. Then Check.

Try it yourself

using UnityEngine;
using UnityEngine.InputSystem;

public class Player : MonoBehaviour
{
    [SerializeField] private float speed = 5f;
    [SerializeField] private float jumpHeight = 1.5f;
    [SerializeField] private float gravity = -9.81f;

    private CharacterController controller;
    private InputAction moveAction;
    private InputAction jumpAction;
    private Vector3 velocity;

    void Start()
    {
        controller = GetComponent<CharacterController>();
        moveAction = InputSystem.actions.FindAction("Move");
        jumpAction = InputSystem.actions.FindAction("Jump");
    }

    void Update()
    {
        if (controller.isGrounded && velocity.y < 0f)
        {
            velocity.y = -2f;
        }

        Vector2 input = moveAction.ReadValue<Vector2>();
        Vector3 move = new Vector3(input.x, 0f, input.y) * speed;

        if (jumpAction.WasPressedThisFrame() && controller.isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }

        velocity.y += gravity * Time.deltaTime;
        controller.Move((move + velocity) * Time.deltaTime);
    }
}

All lessons in Building Real Games

Practice on your own: Unity playground