Menu
CoddyTech

成長する

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

エサを食べると、ヘビの長さは1節分伸びます。新しい節は、移動する前にしっぽの末端があった場所にできます。しっぽが前に移動し、末端が空けたマスを新しい節が埋めるので、ヘビは後ろから伸びます。

しっぽが移動するとそのマスは空くので、まずその位置を記録しておきます。その後、頭がエサに到達したら、そこに節をインスタンス化してリストに追加し、次の移動から追従するようにします。作成しても追加されていない節は動きません。列車も同じように後ろに車両を追加します。

Vector3 back = wagons[wagons.Count - 1].position;
// ... 列車は進み続ける ...
Transform wagon = Instantiate(wagonPrefab, back, Quaternion.identity);
wagons.Add(wagon);

Eat()を呼び出す前に成長させます。Eat()はエサを移動させます。次のレッスンでは、新しい節も含めて、ヘビが占めていないマスを探すようにします。

challenge icon

チャレンジ

中級

食べ物を食べるたびに、しっぽにセグメントが追加されます。

  1. Snakeにpublic Transform segmentPrefab;を追加します(シーンで紐づけます)。
  2. Step()で、しっぽが動く前にVector3 tailEndを保持します。これは最後のセグメントのセル、またはしっぽが空の場合は頭のセルです。
  3. 食べ物を食べたら、Instantiate(segmentPrefab, tailEnd, Quaternion.identity)をtailに追加し、その後Eat()を呼び出します。

「プレイ」を押していくつか食べると、食べるたびにヘビがキューブ1個分大きくなります。その後、「確認」を押します。

自分で試してみよう

using System.Collections.Generic;
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;
    public List<Transform> tail = new List<Transform>();
    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;
        }

        for (int i = tail.Count - 1; i > 0; i--)
        {
            tail[i].position = tail[i - 1].position;
        }
        if (tail.Count > 0)
        {
            tail[0].position = transform.position;
        }
        transform.position = next;

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

    void Die()
    {
        alive = false;
    }
}

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

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