咬到自己
Coddy Unity 3D 贪吃蛇游戏 课程的第 10 课,共 14 课。
蛇头撞到墙壁时会死亡,撞到自己的尾巴时也一样。检查放在同一个位置:头部移动前,检查 next,也就是前方的格子,这样游戏结束时,蛇头会停在原地。
只有一节是安全的。在这一步中,最后一节也会向前移动,离开它所在的格子,所以蛇头沿着尾巴的末端进入那个格子时,不会碰到它。这样一来,由四个方块组成的蛇可以永远绕着一个 2 × 2 的正方形移动。检查时要排除最后一节,所以循环在到达末尾前一位时停止:
// 除最后一项外的每一项
for (int i = 0; i < items.Count - 1; i++)
{
Debug.Log(items[i].name);
}墙壁和尾巴都会致命,游戏因此可能失败。下一章会添加分数,以及重新开始游戏的方式。
挑战
中等碰到自己的尾巴会结束游戏。
- 在
Step()中,通过墙壁检测后,用i < tail.Count - 1遍历尾巴,不包括最后一节。 - 如果
tail[i].position == next,就调用Die()并返回,这样蛇头就不会移动。
按“开始”,让蛇变长,然后转向自己的尾巴:它会停下来。接着按“检查”。
亲手试试
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class Snake : MonoBehaviour
{
public float tick = 0.15f; // 两次移动之间的秒数
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 在线编辑器