Unity 6.3 LTS|2D横スクロールゲームを作ろう④ カメラ追尾と落下復帰を作ろう

横へ広げた2DステージとPlayer、RespawnPoint、DeathZoneの配置 Unity

第4回はステージを横へ広げ、Main CameraがPlayerを追いかけるようにします。さらに、穴へ落ちたPlayerをDeathZoneで見つけ、RespawnPointへ戻します。

今回のミッション

①カメラがPlayerをなめらかに追う、②どの穴へ落ちても検知できる、③スタート地点へ戻ってすぐ操作を再開できる、の3項目を完成させます。

完成イメージ

まず完成した動きを見よう

Playerが右へ進むとカメラも追尾し、足場から落ちると開始位置へ戻ります。実際の制作画面で、3つの動作を確認できています。

STEP 1

落下復帰を4つのブロックに分けよう

① 落ちる足場の下へ移動
② 触れるDeathZoneへ侵入
③ 止める速度を0にする
④ 戻すRespawnPointへ移動

DeathZoneは見えないセンサーです。床のようにPlayerを止めるのではなく、「入ってきた」ことだけをスクリプトへ知らせます。

STEP 2

Groundを複製してステージを広げよう

長さと高さが異なる6個の足場を配置した2Dステージ
Groundを複製し、X位置・Y位置・Scale Xを変えて横長のコースを作りました。

Groundを選び、Ctrl + Dで複製します。複製した足場はPositionとScaleを変えて配置します。すべての足場にBox Collider 2DとGroundレイヤーが必要です。

変更する値役割
Position X足場を左右へ動かす
Position Y足場の高さを変える
Scale X足場の横幅を変える

同じ足場を使うならPrefab化しよう

Groundプレハブを6個配置したHierarchy
青いキューブの印はPrefab Instanceです。親をPlatformsなどの名前でまとめると整理しやすくなります。
Scaleを変えたら、全部同じ大きさになる?

Scene内で各足場のScaleを変えるだけなら、その足場だけのPrefab Overrideになります。他の足場は変わりません。ただし、Transformの変更をPrefabへApplyすると、上書きされていない他のInstanceにも影響します。足場の長さはSceneごとのOverrideとして使い、むやみにApplyしないのが安全です。

STEP 3

Main CameraをPlayerへ追尾させよう

ScriptsフォルダーへCameraFollow2D.csを作り、Main Cameraへ付けます。

ピース1:追いかける目標を用意する
public Transform target;
public Vector2 offset = new Vector2(0f, 1f);
public float smoothTime = 0.2f;

Vector3 followVelocity;

targetにはPlayer、offsetにはPlayerから見たカメラのずれ、smoothTimeには追いつくなめらかさを入れます。

ピース2:Playerの後からカメラを動かす
void LateUpdate()
{
    if (target == null)
    {
        return;
    }

LateUpdate()は通常のUpdateが終わった後に呼ばれます。先にPlayerが動き、その後でカメラが追うため、追尾処理に向いています。

ピース3:目標座標を組み立てる
Vector3 targetPosition =
    new Vector3(
        target.position.x + offset.x,
        target.position.y + offset.y,
        transform.position.z);

XとYはPlayerを基準にしますが、Zは現在のカメラの値を残します。2DカメラのZを0にするとSpriteと同じ奥行きへ移動し、映らなくなることがあります。

ピース4:急に移動せず、なめらかに近づく
transform.position =
    Vector3.SmoothDamp(
        transform.position,
        targetPosition,
        ref followVelocity,
        smoothTime);
}

SmoothDampは現在位置から目標位置へ少しずつ近づけます。ref followVelocityは、なめらかな変化を続けるためにUnityが利用する速度の記録です。

CameraFollow2D.csの全コード
using UnityEngine;

public class CameraFollow2D : MonoBehaviour
{
    public Transform target;
    public Vector2 offset = new Vector2(0f, 1f);
    public float smoothTime = 0.2f;

    Vector3 followVelocity;

    void LateUpdate()
    {
        if (target == null)
        {
            return;
        }

        Vector3 targetPosition =
            new Vector3(
                target.position.x + offset.x,
                target.position.y + offset.y,
                transform.position.z);

        transform.position =
            Vector3.SmoothDamp(
                transform.position,
                targetPosition,
                ref followVelocity,
                smoothTime);
    }
}
Main Camera / Camera Follow 2D
Target      = Player
Offset      = (0, 1)
Smooth Time = 0.2
STEP 4

RespawnPointとDeathZoneを作ろう

Player、足場、RespawnPoint、長いDeathZoneを配置したUnity Scene
緑色の長い枠がDeathZoneです。すべての穴の下を覆うように配置します。
RespawnPoint
戻る場所
↔
DeathZone
落下を見つける場所
  1. Hierarchyの何もない場所でCreate Emptyを選び、RespawnPointを作る
  2. Playerの開始位置へRespawnPointを置く
  3. もう1つEmptyを作り、DeathZoneにする
  4. DeathZoneへBox Collider 2Dを追加する
  5. Is Triggerをオンにし、全ステージの下を覆う大きさにする
  6. Tagへ新しいDeathZoneを作り、DeathZoneへ設定する
RespawnPointをPlayerの子にしない

Playerの子にすると、Playerと一緒に落下して戻る場所まで動きます。RespawnPointとDeathZoneはScene直下に置きます。

STEP 5

落ちたPlayerを安全に戻そう

PlayerRespawn2D.csを作り、Playerへ追加します。

ピース1:DeathZoneだけを見分ける
void OnTriggerEnter2D(Collider2D other)
{
    if (!other.CompareTag("DeathZone"))
    {
        return;
    }

    Respawn();
}

OnTriggerEnter2DはTriggerへ入ったときに呼ばれます。!は「~ではない」という意味なので、DeathZone以外なら処理を終了します。

ピース2:速度を消してから位置を戻す
rb.linearVelocity = Vector2.zero;
rb.angularVelocity = 0f;
rb.position = returnPosition;

位置だけを戻すと落下速度が残り、戻った直後も下へ動くことがあります。左右・上下の速度と回転速度を0にしてから、Rigidbody2Dの位置を変更します。

PlayerRespawn2D.csの全コード
using UnityEngine;

[RequireComponent(typeof(Rigidbody2D))]
public class PlayerRespawn2D : MonoBehaviour
{
    public Transform respawnPoint;

    Rigidbody2D rb;
    Vector2 startPosition;

    void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        startPosition = rb.position;
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (!other.CompareTag("DeathZone"))
        {
            return;
        }

        Respawn();
    }

    void Respawn()
    {
        Vector2 returnPosition =
            respawnPoint != null
                ? respawnPoint.position
                : startPosition;

        rb.linearVelocity = Vector2.zero;
        rb.angularVelocity = 0f;
        rb.position = returnPosition;
    }
}

respawnPoint != null ? A : Bは、「RespawnPointが設定されていればA、設定されていなければB」を選ぶ書き方です。参照を忘れても、Awakeで覚えた開始位置へ戻れます。

PUZZLE 1

処理の順番を並べよう

次の処理を正しい順番へ並べてください。

  1. RespawnPointへ移動する
  2. DeathZoneへ触れる
  3. 落下速度を0にする
  4. Playerが足場から落ちる
答えを見る

4 → 2 → 3 → 1です。速度を消してから位置を戻すのがポイントです。

PUZZLE 2

穴埋めで復帰コードを完成させよう

if (!other.①("DeathZone"))
{
    return;
}

rb.linearVelocity = Vector2.②;
rb.position = ③;
答えを見る
  1. CompareTag
  2. zero
  3. returnPosition
ERROR CHECK

うまく戻らないときの確認

症状確認する場所
落ちても反応しないDeathZoneのBox Collider 2DでIs Triggerがオンか。PlayerにRigidbody2Dがあるか。
どこか違う場所へ戻るPlayer Respawn 2DのRespawn Point欄へ、Scene直下のRespawnPointを登録したか。
戻った直後に再び落ちるRespawnPointが床より少し上にあり、床のCollider内へ埋まっていないか。
カメラが動かないMain CameraのTarget欄へPlayerを登録したか。
Playerが映らないカメラのZが通常の-10付近で保たれているか。
CHECK

3項目を再生確認しよう

  • カメラがPlayerをなめらかに追いかける
  • Playerが足場から落ちるとDeathZoneに触れる
  • 落下後、RespawnPointへ戻り、そのまま操作を再開できる

今回の制作では3項目すべて確認できました。

次回へ

着地の光と音を作ろう

第5回へ進む。光の輪に着地音を付けよう →

コメント

タイトルとURLをコピーしました