墙壁
Coddy Unity 3D 贪吃蛇游戏 课程的第 4 课,共 14 课。
棋盘的格子在 x 轴和 z 轴上的范围都是 -7 到 7。棋盘以 0 为中心,因此一个测试就能检查两侧:超过任意一侧边缘时,Mathf.Abs(x) > 7 为真。
在蛇头移动到即将进入的格子之前,先检查这个格子。这样,撞墙的蛇会停在最后一个格子上,而不会停在边界外。在边缘为 4 的较小棋盘上:
Vector3 next = transform.position + direction;
if (Mathf.Abs(next.x) > 4) { Die(); return; }
transform.position = next;撞墙会让蛇彻底停下来。用 bool 来让 Update() 先进行检查即可做到这一点:放在开头的 return 会同时跳过按键处理和计时器。
挑战
简单撞到墙壁会结束游戏。
- 添加
public int edge = 7;和public bool alive = true; - 在
Step()中设置方向后,添加Vector3 next = transform.position + direction;。如果超出棋盘范围(Mathf.Abs(next.x) > edge,或 z 超出范围),则调用Die()并返回;否则移动到 next。 void Die() { alive = false; };让Update()以if (!alive) return;开始。
点击“运行”,让蛇撞向墙壁:蛇会停在最后一个格子上。然后点击“检查”。
亲手试试
using UnityEngine;
using UnityEngine.InputSystem;
public class Snake : MonoBehaviour
{
public float tick = 0.15f; // 两次移动之间的秒数
private float timer;
private Vector3 direction = Vector3.right; // 蛇头上一步移动的方向
private Vector3 nextDirection = Vector3.right; // 等待下一步执行的转向
void Update()
{
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;
transform.position += direction;
}
}
Unity 3D 贪吃蛇游戏中的所有课
自己练习: Unity 在线编辑器