Menu
CoddyTech

壁

Coddyの「Unityゲーム:3Dスネーク」コースのレッスン 4/14。

ボードのセルは、x 軸と z 軸のそれぞれで -7 から 7 までです。ボードの中心を 0 にすると、1つのテストで両側を確認できます。Mathf.Abs(x) > 7 は、どちらかの端を越えると true になります。

頭が次に進もうとしているセルを、そこへ移動する前にテストしましょう。そうすれば、壁にぶつかったヘビは境界の内側で止まらず、最後のセルにとどまります。端が 4 の小さなボードでは、次のようになります。

Vector3 next = transform.position + direction;
if (Mathf.Abs(next.x) > 4) { Die(); return; }
transform.position = next;

壁にぶつかると、ヘビはそのまま停止します。Update() が最初にテストする bool を使えば実現できます。先頭の return によって、キー入力とタイマーの両方をスキップできます。

challenge icon

チャレンジ

簡単

壁にぶつかるとゲームが終了します。

  1. public int edge = 7; と public bool alive = true; を追加します。
  2. Step() で、direction を設定した後に Vector3 next = transform.position + direction; を追加します。ボードの外に出た場合(Mathf.Abs(next.x) > edge、または z):Die() を呼び出して return します。それ以外の場合は next に移動します。
  3. void Die() { alive = false; } を追加し、Update() の最初に if (!alive) return; を記述します。

「プレイ」を押して壁に向かって操作すると、ヘビは最後のマスで止まります。その後、「確認」を押します。

自分で試してみよう

using UnityEngine;
using UnityEngine.InputSystem;

public class Snake : MonoBehaviour
{
    public float tick = 0.15f;   // 2回の移動の間隔(秒)
    private float timer;
    private Vector3 direction = Vector3.right;       // 直前の移動で頭が進んだ方向
    private Vector3 nextDirection = Vector3.right;   // 次の移動で適用される方向転換

    void Update()
    {
        Keyboard keyboard = Keyboard.current;
        if (keyboard != null)
        {
            if (keyboard.upArrowKey.wasPressedThisFrame || keyboard.wKey.wasPressedThisFrame) Turn(Vector3.forward);
            if (keyboard.downArrowKey.wasPressedThisFrame || keyboard.sKey.wasPressedThisFrame) Turn(Vector3.back);
            if (keyboard.leftArrowKey.wasPressedThisFrame || keyboard.aKey.wasPressedThisFrame) Turn(Vector3.left);
            if (keyboard.rightArrowKey.wasPressedThisFrame || keyboard.dKey.wasPressedThisFrame) Turn(Vector3.right);
        }

        timer += Time.deltaTime;
        if (timer >= tick)
        {
            timer -= tick;
            Step();
        }
    }

    void Turn(Vector3 newDirection)
    {
        if (newDirection != -direction)
        {
            nextDirection = newDirection;
        }
    }

    void Step()
    {
        direction = nextDirection;
        transform.position += direction;
    }
}

Unityゲーム:3Dスネークのすべてのレッスン

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