Menu
CoddyTech

Fall and Respawn

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

challenge icon

Challenge

Medium

A fall should put the player back.

  1. In Player, add [SerializeField] private float fallY = -5f; and a respawn point, set to the start position in Start().
  2. Add public void SetCheckpoint(Vector3 point) that sets the respawn point.
  3. Below fallY: set controller.enabled = false, move to the respawn point, enable it again and clear velocity.

Press Play and jump off: you are back on the pad. 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;
    private MovingPlatform platform;

    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;
        Vector3 motion = (move + velocity) * Time.deltaTime;
        if (platform != null)
        {
            motion += platform.delta;
            platform = null;
        }
        controller.Move(motion);
    }

    void OnControllerColliderHit(ControllerColliderHit hit)
    {
        if (hit.normal.y > 0.5f && hit.gameObject.TryGetComponent(out MovingPlatform moving))
        {
            platform = moving;
        }
    }
}

All lessons in Building Real Games

Practice on your own: Unity playground