Menu
CoddyTech

Tomber et réapparaître

Fait partie de la section Créer de vrais jeux du Journey Unity de Coddy. Leçon 52 sur 60.

challenge icon

Défi

Moyen

Une chute devrait ramener le joueur à sa position de départ.

  1. Dans Player, ajoute [SerializeField] private float fallY = -5f; et un point de réapparition, défini sur la position de départ dans Start().
  2. Ajoute public void SetCheckpoint(Vector3 point) qui définit le point de réapparition.
  3. Sous fallY : définis controller.enabled = false, déplace le joueur vers le point de réapparition, réactive le contrôleur, puis réinitialise velocity.

Appuie sur « Jouer » et saute dans le vide : tu reviens sur la plateforme. Puis appuie sur « Vérifier ».

Essayez vous-même

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

Toutes les leçons de Créer de vrais jeux

Entraînez-vous par vous-même : Playground Unity