Menu
CoddyTech

추락 후 다시 시작

Coddy Unity 여정의 실제 게임 만들기 섹션에 포함된 레슨. 60개 중 52번째.

challenge icon

챌린지

중급

떨어지면 플레이어가 다시 시작 위치로 돌아와야 합니다.

  1. Player에 [SerializeField] private float fallY = -5f;와 리스폰 지점을 추가하고, Start()에서 시작 위치로 설정하세요.
  2. 리스폰 지점을 설정하는 public void SetCheckpoint(Vector3 point)를 추가하세요.
  3. fallY보다 낮아지면 controller.enabled = false로 설정하고, 리스폰 지점으로 이동한 다음 다시 활성화하고 velocity를 초기화하세요.

‘플레이’를 눌러 뛰어내리세요. 패드 위로 돌아옵니다. 그런 다음 ‘확인’을 누르세요.

직접 해보기

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

실제 게임 만들기의 모든 레슨

직접 연습해 보세요: Unity 플레이그라운드