Menu
CoddyTech

しっぽ

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

しっぽは、頭の後ろにあるもの tail[0] から末尾までのセグメントのリスト List<Transform> tail です。シーンでは、Inspector で設定した Tail1 と Tail2 の2つのセグメントを持つヘビが開始します。

各ステップで、各セグメントは前にあるセグメントのセルに移動し、tail[0] は頭のセルに移動します。順序が重要です。前から進めると、tail[1] は、すでに移動した tail[0] のセルをコピーするため、しっぽ全体が1つのセルに重なってしまいます。後ろから進めると、各セグメントはまだ変更されていないセルをコピーします。乗客が1つ後ろの席に移動する場合も同じです。

string[] seats = { "Ana", "Ben", "Cy" };
for (int i = seats.Length - 1; i > 0; i--)
{
    seats[i] = seats[i - 1];
}
seats[0] = "Dee";   // Dee, Ana, Ben

頭は、tail[0] が元のセルに移動した後、最後に移動します。

challenge icon

チャレンジ

中級

ヘビに、頭の後を追う尻尾を付けましょう。

  1. Snakeで、using System.Collections.Generic;とpublic List<Transform> tail = new List<Transform>();を追加します(シーンにTail1とTail2を追加します)。
  2. Step()で、頭が動く直前に、後ろから各セグメントが前のセグメントのセルに移動するようにします。tail[0]は頭がいたセルに移動します。

「プレイ」を押して操作すると、尻尾が頭の通った道をたどります。その後、「確認」を押します。

自分で試してみよう

using UnityEngine;
using UnityEngine.InputSystem;

public class Snake : MonoBehaviour
{
    public float tick = 0.15f;   // 2回の移動の間隔(秒)
    public int edge = 7;         // 盤面のマスは-edgeからedgeまで
    public bool alive = true;
    private float timer;
    private Vector3 direction = Vector3.right;       // 直前の移動で頭が進んだ方向
    private Vector3 nextDirection = Vector3.right;   // 次の移動で適用される方向転換

    void Update()
    {
        if (!alive) return;

        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;
        Vector3 next = transform.position + direction;
        if (Mathf.Abs(next.x) > edge || Mathf.Abs(next.z) > edge)
        {
            Die();
            return;
        }

        transform.position = next;

        if (GameManager.Instance.IsFood(next))
        {
            GameManager.Instance.Eat();
        }
    }

    void Die()
    {
        alive = false;
    }
}

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

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