Menu
CoddyTech

キルゾーン

CoddyのUnityジャーニー「物理演算とゲームプレイ」セクションの一部。レッスン 19/71。

キルゾーンは、プレイヤーが到達してはいけない場所に設置するトリガーです。溶岩、トゲ、レベルの下にある何もない空間などが該当します。そこに入ると、プレイヤーはスポーン地点に戻されます。ここでは溶岩自体のスクリプトで処理し、スポーン地点はInspectorで設定したTransformフィールドに格納します:

public Transform spawnPoint;

void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Player"))
    {
        other.transform.position = spawnPoint.position;
        other.attachedRigidbody.linearVelocity = Vector3.zero;
    }
}

other.attachedRigidbodyは、侵入したコライダーが属するRigidbodyです。transform.positionを設定するとプレイヤーがテレポートします。これはリスポーンに必要な処理です。ただし、Rigidbodyはジャンプ中の速度を保持します。毎秒10ユニットの速度で落ちてきたプレイヤーは、スポーン地点に到着しても毎秒10ユニットの速度で落下し続け、溶岩に走り込んだプレイヤーは走り続けて、まっすぐ溶岩に戻ってしまいます。linearVelocityをVector3.zeroに設定すると、静止した状態で到着します。タグの確認により、溶岩に落ちたほかのものはその場に留まります。

challenge icon

チャレンジ

簡単

プレイヤーがリスポーンできるようにします。このスクリプトはプレイヤーに付いているため、transform と body を動かし、other は動かしません。

  1. Start() で、Vector3 respawn フィールドに transform.position を設定します。
  2. OnTriggerEnter(Collider other) で、other.CompareTag("Checkpoint") のとき、respawn = transform.position; を設定します。
  3. other.CompareTag("KillZone") のとき、transform.position = respawn; と body.linearVelocity = Vector3.zero; を設定します。

「プレイ」を押して、橋から歩いて落ちます。その後、「確認」を押します。

自分で試してみよう

using UnityEngine;

public class Player : MonoBehaviour
{
    public float force = 12f;
    Rigidbody body;
    Vector3 input;
    // respawn: プレイヤーが戻ってくる場所

    void Start()
    {
        body = GetComponent<Rigidbody>();
    }

    void Update()
    {
        input = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
    }

    void FixedUpdate()
    {
        body.AddForce(input * force);
    }

    // Checkpoint: プレイヤーの現在位置を記憶する。KillZone: その場所に戻り、静止した状態にする。
}

物理演算とゲームプレイのすべてのレッスン

自分で練習してみよう: Unityプレイグラウンド