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. 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, so a snake that hits a wall stays on the last cell instead of ending inside the border. On a smaller board with edge 4:
Vector3 next = transform.position + direction;
if (Mathf.Abs(next.x) > 4) { Die(); return; }
transform.position = next;Hitting a wall stops the snake for good. A bool that Update() tests first does that: a return at the top skips the keys and the timer alike.
Challenge
EasyHitting a wall ends the game.
- Add
public int edge = 7;andpublic bool alive = true; - In
Step(), after setting direction,Vector3 next = transform.position + direction;. Off the board (Mathf.Abs(next.x) > edge, or z):Die()and return; else move to next. void Die() { alive = false; };Update()starts withif (!alive) return;
Press Play and steer into a wall: the snake stops on the last cell. Then 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;
}
}
All lessons in Unity Game: Snake 3D
Practice on your own: Unity playground