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, grows, and dies on the walls or its own tail. Snake runs the head; GameManager stays empty until the food comes. Play runs the game; Check grades it.

The cells are one unit wide, on whole numbers from -7 to 7. The snake never glides: it jumps a whole cell on a tick, a fixed beat, and stands still in between. A beat is a timer: add Time.deltaTime every frame, and when it reaches the beat, act and take the beat off:

timer += Time.deltaTime;
if (timer >= 0.5f)
{
    timer -= 0.5f;
    Step();
}

Taking the beat off, instead of setting the timer to 0, keeps the bit of a frame that went past it, so the beat does not drift late. Use the tick field, not a number.

challenge icon

Challenge

Easy

Make the head step one cell every tick.

  1. In Snake, add private float timer;
  2. In Update(), add Time.deltaTime to timer; when timer >= tick, take tick off it and call Step().
  3. In Step(), add direction to transform.position.

Press Play: the head steps right, cell by cell, off the board for now. Then 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
    }
}

All lessons in Unity Game: Snake 3D

Practice on your own: Unity playground