越来越快
Coddy Unity 3D 贪吃蛇游戏 课程的第 13 课,共 14 课。
Snake 会随着自身变长而变得更难:每吃到一个食物,tick 就会缩短一点,因此 Snake 移动得更快。下限能让游戏保持可玩:它是 tick 可以达到的最短时长。
Mathf.Max 会返回两个数字中较大的那个,因此可以用来设定下限:Mathf.Max(value, floor) 永远不会小于 floor。炮塔每次升级后都会加快射击速度,但射击间隔不会短于 0.2 秒:
cooldown = Mathf.Max(cooldown - 0.05f, 0.2f);Mathf.Min 正好相反,它用于设定上限。混淆两者很容易出错:如果使用 Min,上面的 cooldown 会在第一次升级时降到 0.2。Update() 中的计时器会在每一帧读取 tick,因此缩短后的 tick 会从下一步开始生效。
挑战
困难蛇每吃到食物,速度都会加快。
- 在
Snake中,添加public float speedUp = 0.005f;和public float minTick = 0.08f; - 吃到食物时,让 tick 缩短 speedUp,但不能小于 minTick:
tick = Mathf.Max(tick - speedUp, minTick);
按“开始”并吃到食物:蛇每次都会稍微加快一点。然后点击“检查”。
亲手试试
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;
}
for (int i = 0; i < tail.Count - 1; i++)
{
if (tail[i].position == next)
{
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;
GameManager.Instance.GameOver();
}
}
Unity 3D 贪吃蛇游戏中的所有课
自己练习: Unity 在线编辑器