しっぽ
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] が元のセルに移動した後、最後に移動します。
チャレンジ
中級using System.Collections.Generic;とpublic List<Transform> tail = new List<Transform>();を追加します。シーン内でTail1とTail2を使ってリストを埋めます。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;
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。