The Walls
Lesson 4 of 14 in Coddy's Unity Game: Snake 3D course.
The board's cells run from -7 to 7 on x and on z, so a cell is on the board while both its x and its z are between -7 and 7. With the board centred on 0, one test covers both sides: Mathf.Abs(x) > 7 is true past either edge.
Test the cell the head is about to enter, before it moves there. Then a snake that hits a wall stays on the last cell of the board instead of ending up inside the border. A rook on a chess board numbered 0 to 7 is checked the same way:
Vector3 target = transform.position + move;
if (target.x < 0 || target.x > 7 || target.z < 0 || target.z > 7)
{
return; // off the board: the rook stays
}
transform.position = target;Hitting a wall ends the game, and the snake stops for good. A bool that Update() tests first does that: a return at the top skips the keys and the timer alike.
Challenge
Easy- Add
public int edge = 7;(the board's cells run from-edgetoedge) andpublic bool alive = true;. - In
Step(), after settingdirection, work outnext, the cell the head is about to enter. If it is off the board, callDie()and return without moving; otherwise move the head tonext. - Write
void Die(), which setsaliveto false. - Start
Update()with a return when the snake is not alive, so a dead snake neither turns nor steps.
Press Play, steer into a wall, then press Check.
Try it yourself
using UnityEngine;
using UnityEngine.InputSystem;
public class Snake : MonoBehaviour
{
public float tick = 0.15f; // seconds between two steps
private float timer;
private Vector3 direction = Vector3.right; // the way the head moved on its last step
private Vector3 nextDirection = Vector3.right; // the turn waiting for the next step
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;
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.