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. The press only changes direction; Step() still moves the head, on the next tick:

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

An arrow and its letter are two keys, joined with ||. Keyboard.current is null on a device with no keyboard, so check it once at the top.

challenge icon

Challenge

Easy

Steer the snake with the arrows or WASD.

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

Press Play, click the game and steer: the head turns on the next step. Then 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;
    }
}

All lessons in Unity Game: Snake 3D

Practice on your own: Unity playground