大きくなる
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()はエサを移動させます。次のレッスンでは、新しい節も含めて、ヘビが占めていないマスを探すようにします。
チャレンジ
中級シーンでは、SnakeのsegmentPrefabに尻尾と同じようなキューブを設定します。
public Transform segmentPrefab;を追加します。Step()で、尻尾が動く前に、尻尾が空の場合は頭のセル、そうでなければ尻尾の最後のセグメントのセルをVector3 tailEndに保持します。- 頭が食べ物の上にあるとき、
tailEndにsegmentPrefabをインスタンス化してtailに追加し、その後Eat()を呼び出します。
Playを押していくつか食べてから、Checkを押します。
自分で試してみよう
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;
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。