Menu
CoddyTech

Caer y reaparecer

Parte de la sección Creación de juegos reales del Journey de Unity de Coddy. Lección 52 de 60.

challenge icon

Desafío

Intermedio

Una caída debería devolver al jugador a su posición anterior.

  1. En Player, añade [SerializeField] private float fallY = -5f; y un punto de reaparición, establecido en la posición inicial en Start().
  2. Añade public void SetCheckpoint(Vector3 point) para establecer el punto de reaparición.
  3. Cuando esté por debajo de fallY: establece controller.enabled = false, mueve al jugador al punto de reaparición, vuelve a habilitarlo y borra velocity.

Pulsa «Jugar» y salta al vacío: volverás a la plataforma. Después, pulsa «Comprobar».

Pruébalo tú mismo

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

Todas las lecciones de Creación de juegos reales

Practica por tu cuenta: Playground de Unity