Menu
CoddyTech

No U-Turns

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

A snake that turns straight back runs into its own neck, so a turn to the opposite way is ignored. The opposite of a direction is its negative: while the snake moves right, -direction is Vector3.left.

Comparing with direction is not enough while a press changes it at once: moving right, a player taps up, then left, inside one tick. Up is allowed, then left is checked against up and allowed too, and the next step goes back over the neck.

So keep two directions: direction, the way the head moved last, and nextDirection, the turn waiting for the next step. A key changes nextDirection after comparing with direction, and the step makes the waiting turn real.

challenge icon

Challenge

Easy

Stop the snake from turning straight back onto its neck.

  1. Add private Vector3 nextDirection = Vector3.right; and void Turn(Vector3 newDirection): set nextDirection unless newDirection == -direction.
  2. In Update(), each key calls Turn with its direction instead of setting direction.
  3. At the start of Step(), set direction = nextDirection;

Press Play and press left while moving right: the snake keeps going right. 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;

    void Update()
    {
        Keyboard keyboard = Keyboard.current;
        if (keyboard != null)
        {
            if (keyboard.upArrowKey.wasPressedThisFrame || keyboard.wKey.wasPressedThisFrame) direction = Vector3.forward;
            if (keyboard.downArrowKey.wasPressedThisFrame || keyboard.sKey.wasPressedThisFrame) direction = Vector3.back;
            if (keyboard.leftArrowKey.wasPressedThisFrame || keyboard.aKey.wasPressedThisFrame) direction = Vector3.left;
            if (keyboard.rightArrowKey.wasPressedThisFrame || keyboard.dKey.wasPressedThisFrame) direction = Vector3.right;
        }

        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