Menu
CoddyTech

Fallen und respawnen

Teil des Abschnitts Echte Spiele entwickeln der Unity-Journey von Coddy. Lektion 52 von 60.

challenge icon

Aufgabe

Mittel

Ein Sturz sollte den Spieler zurücksetzen.

  1. Füge in Player [SerializeField] private float fallY = -5f; und einen Wiederbelebungspunkt hinzu, der in Start() auf die Startposition gesetzt wird.
  2. Füge public void SetCheckpoint(Vector3 point) hinzu, das den Wiederbelebungspunkt festlegt.
  3. Wenn du unter fallY bist: Setze controller.enabled = false, bewege dich zum Wiederbelebungspunkt, aktiviere ihn wieder und setze velocity zurück.

Drücke „Spielen“ und springe herunter: Du bist wieder auf der Plattform. Drücke anschließend „Prüfen“.

Probier es selbst

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;
        }
    }
}

Alle Lektionen in Echte Spiele entwickeln

Übe selbstständig: Unity-Playground