自分を噛む
Coddyの「Unityゲーム:3Dスネーク」コースのレッスン 10/14。
ヘビは、壁にぶつかるときと同じように、頭が自分のしっぽにぶつかると死にます。判定は同じ場所、つまり頭が動く前に前方のセルである next に対して行うため、ゲーム終了時に頭はその場にとどまります。
1つのセグメントだけなら安全です。このステップでは最後のセグメントも上へ移動してセルから出るため、しっぽの端を追ってそのセルに入った頭が、しっぽに触れることはありません。4つの立方体からなるヘビは、この方法で2×2の正方形を永久に回り続けられます。判定では、末尾の1つ手前で止めて、最後のセグメントを除外します。
// 最後の要素を除くすべての要素
for (int i = 0; i < items.Count - 1; i++)
{
Debug.Log(items[i].name);
}壁としっぽのどちらにぶつかってもゲームオーバーになるようになり、次の章ではスコアと、もう一度プレイする方法を追加します。
チャレンジ
中級しっぽに噛みつくとゲームが終了します。
Step()で壁の判定を行った後、i < tail.Count - 1でしっぽをループし、最後のセグメントは除外します。tail[i].position == nextの場合は、Die()を呼び出してreturnし、頭が動かないようにします。
「プレイ」を押して、ヘビを伸ばしてしっぽの方向に曲がります。ヘビが止まったら、「確認」を押します。
自分で試してみよう
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>();
public Transform segmentPrefab;
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;
}
Vector3 tailEnd = tail.Count > 0 ? tail[tail.Count - 1].position : transform.position;
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))
{
tail.Add(Instantiate(segmentPrefab, tailEnd, Quaternion.identity));
GameManager.Instance.Eat();
}
}
public bool Occupies(Vector3 cell)
{
if (transform.position == cell) return true;
foreach (Transform segment in tail)
{
if (segment.position == cell) return true;
}
return false;
}
void Die()
{
alive = false;
}
}
Unityゲーム:3Dスネークのすべてのレッスン
自分で練習してみよう: Unityプレイグラウンド