Fall and Respawn
Part of the Building Real Games section of Coddy's Unity journey. Lesson 52 of 60.
Challenge
MediumA fall should put the player back.
- In
Player, add[SerializeField] private float fallY = -5f;and a respawn point, set to the start position inStart(). - Add
public void SetCheckpoint(Vector3 point)that sets the respawn point. - Below
fallY: setcontroller.enabled = false, move to the respawn point, enable it again and clearvelocity.
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
10Project: 3D Platformer
The CourseMoving Platforms2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input SwapPractice on your own: Unity playground