Menu
CoddyTech

落下とリスポーン

CoddyのUnityジャーニー「本格的なゲームを作る」セクションの一部。レッスン 52/60。

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プレイグラウンド