Menu
CoddyTech

Rơi xuống và xuất hiện lại

Thuộc phần Xây dựng trò chơi thực tế trong hành trình Unity của Coddy. Bài học 52 trên 60.

challenge icon

Thử thách

Trung bình

Khi rơi, người chơi cần quay lại vị trí ban đầu.

  1. Trong Player, thêm [SerializeField] private float fallY = -5f; và một điểm hồi sinh, đặt điểm này ở vị trí bắt đầu trong Start().
  2. Thêm public void SetCheckpoint(Vector3 point) để đặt điểm hồi sinh.
  3. Khi vị trí thấp hơn fallY: đặt controller.enabled = false, di chuyển đến điểm hồi sinh, bật lại rồi xóa velocity.

Nhấn Chơi rồi nhảy xuống: bạn sẽ quay lại bệ. Sau đó nhấn Kiểm tra.

Tự làm thử

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

Tất cả bài học trong Xây dựng trò chơi thực tế

Tự luyện tập: Playground Unity