Menu
CoddyTech

The Board

Lesson 1 of 14 in Coddy's Unity Game: Snake 3D course.

In this course you build Snake in 3D: a snake of cubes on a 15 by 15 board seen from above. It moves one cell at a time, turns with the arrows or WASD, eats food, grows, and dies on the walls or on its own tail. Two scripts run it: Snake on the head, and GameManager, which stays empty until the food arrives in the next chapter.

The cells are one unit wide and centred on whole numbers: x and z run from -7 to 7, and every cell sits at y 0. The snake never glides between cells. It jumps a whole cell on a tick, a fixed beat such as 0.15 seconds, and stands still in between.

A beat in Unity is a timer: add Time.deltaTime on every frame, and when the timer reaches the interval, act and take the interval off. This beacon blinks once a second:

public Light beacon;
public float interval = 1f;
private float timer;

void Update()
{
    timer += Time.deltaTime;
    if (timer >= interval)
    {
        timer -= interval;
        beacon.enabled = !beacon.enabled;
    }
}

Taking the interval off, instead of setting the timer back to 0, keeps the part of a frame that went past the interval, so the beat does not drift late.

challenge icon

Challenge

Easy

The head is a green cube on the cell (-3, 0, 0). Snake has tick, 0.15 seconds, and direction, Vector3.right.

  1. Add a private float timer;.
  2. In Update(), count the timer up by Time.deltaTime. When it reaches tick, take tick off it and call Step().
  3. In Step(), move the head one cell along direction.

Press Play and watch the head step to the right. It leaves the board for now: the walls come in lesson 4. Then press Check.

Try it yourself

using UnityEngine;

public class Snake : MonoBehaviour
{
    public float tick = 0.15f;   // seconds between two steps
    private Vector3 direction = Vector3.right;

    void Update()
    {
        // Every tick seconds, take one Step()
    }

    void Step()
    {
        // Move the head one cell along direction
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Game: Snake 3D