不许掉头
Coddy Unity 3D 贪吃蛇游戏 课程的第 3 课,共 14 课。
蛇如果直接转向相反方向,就会撞到自己的脖子,因此会忽略反方向的转向。方向的相反方向就是它的负方向:蛇向右移动时,-direction 是 Vector3.left。
按键会立即改变方向,因此只和 direction 比较还不够:蛇向右移动时,玩家在一个 tick 内先按上,再按左。向上转向是允许的,接着将向左转向与向上方向比较,也会允许它,下一步就会撞回自己的脖子。
所以要保留两个方向:direction,也就是头部上次移动的方向;以及 nextDirection,也就是等待下一步执行的转向。按键会先将新方向与 direction 比较,再更新 nextDirection;移动时再真正执行等待中的转向。
挑战
简单阻止蛇直接掉头,转向自己的脖子。
- 添加
private Vector3 nextDirection = Vector3.right;和void Turn(Vector3 newDirection):除非newDirection == -direction,否则设置 nextDirection。 - 在
Update()中,每个按键都调用Turn并传入对应的方向,而不是设置 direction。 - 在
Step()开始时,设置direction = nextDirection;
按“开始”,然后在向右移动时按左键:蛇会继续向右移动。然后按“检查”。
亲手试试
using UnityEngine;
using UnityEngine.InputSystem;
public class Snake : MonoBehaviour
{
public float tick = 0.15f; // 每两步之间的间隔秒数
private float timer;
private Vector3 direction = Vector3.right;
void Update()
{
Keyboard keyboard = Keyboard.current;
if (keyboard != null)
{
if (keyboard.upArrowKey.wasPressedThisFrame || keyboard.wKey.wasPressedThisFrame) direction = Vector3.forward;
if (keyboard.downArrowKey.wasPressedThisFrame || keyboard.sKey.wasPressedThisFrame) direction = Vector3.back;
if (keyboard.leftArrowKey.wasPressedThisFrame || keyboard.aKey.wasPressedThisFrame) direction = Vector3.left;
if (keyboard.rightArrowKey.wasPressedThisFrame || keyboard.dKey.wasPressedThisFrame) direction = Vector3.right;
}
timer += Time.deltaTime;
if (timer >= tick)
{
timer -= tick;
Step();
}
}
void Step()
{
transform.position += direction;
}
}
Unity 3D 贪吃蛇游戏中的所有课
自己练习: Unity 在线编辑器