Menu
CoddyTech

Steer

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

The snake turns with the arrow keys or WASD. The camera looks down at the board from the front edge, so up the screen is along +z, Vector3.forward, and down is Vector3.back. Vector3.up points at the sky: a head moved by it would rise off the board.

A turn happens once per press, so read the keys with wasPressedThisFrame from the Input System. The press only changes direction. Step() still moves the head, on the next tick, so the snake keeps its beat. A rover that heads toward the right of the screen when D is pressed:

Keyboard keyboard = Keyboard.current;
if (keyboard != null && keyboard.dKey.wasPressedThisFrame)
{
    heading = Vector3.right;
}

The Input System has no axes on the keyboard: an arrow and its letter are two keys, joined with ||. Keyboard.current is null on a device with no keyboard, so read it once at the top and check it.

challenge icon

Challenge

Easy
  1. Add using UnityEngine.InputSystem; to Snake.
  2. At the top of Update(), read Keyboard.current. A press of the up arrow or W sets direction to Vector3.forward; the down arrow or S to Vector3.back; the left arrow or A to Vector3.left; the right arrow or D to Vector3.right.
  3. Leave Step() as it is: the head turns on the next tick.

Press Play, click the game and steer, then press Check.

Try it yourself

using UnityEngine;

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

    void Update()
    {
        timer += Time.deltaTime;
        if (timer >= tick)
        {
            timer -= tick;
            Step();
        }
    }

    void Step()
    {
        transform.position += 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