The Tail
Lesson 7 of 14 in Coddy's Unity Game: Snake 3D course.
The tail is a list of segments, List<Transform> tail, from the one behind the head, tail[0], to the end. The scene starts the snake with two segments, Tail1 and Tail2, set in the Inspector.
On each step every segment takes the cell of the one in front of it, and tail[0] takes the head's cell. The order matters. Going from the front, tail[1] would copy the cell tail[0] has already moved to, and the whole tail would pile onto one cell. Going from the back, each segment copies a cell that has not changed yet. Passengers moving back one seat work the same way:
string[] seats = { "Ana", "Ben", "Cy" };
for (int i = seats.Length - 1; i > 0; i--)
{
seats[i] = seats[i - 1];
}
seats[0] = "Dee"; // Dee, Ana, BenThe head moves last, once tail[0] has taken its old cell.
Challenge
Medium- Add
using System.Collections.Generic;andpublic List<Transform> tail = new List<Transform>();. The scene fills it with Tail1 and Tail2. - In
Step(), right before the head moves, move the tail: each segment, from the back, takes the cell of the one in front of it, andtail[0]takes the head's cell.
Press Play and steer: the tail follows the head's path. Then press Check.
Try it yourself
using UnityEngine;
using UnityEngine.InputSystem;
public class Snake : MonoBehaviour
{
public float tick = 0.15f; // seconds between two steps
public int edge = 7; // the board's cells run from -edge to edge
public bool alive = true;
private float timer;
private Vector3 direction = Vector3.right; // the way the head moved on its last step
private Vector3 nextDirection = Vector3.right; // the turn waiting for the next step
void Update()
{
if (!alive) return;
Keyboard keyboard = Keyboard.current;
if (keyboard != null)
{
if (keyboard.upArrowKey.wasPressedThisFrame || keyboard.wKey.wasPressedThisFrame) Turn(Vector3.forward);
if (keyboard.downArrowKey.wasPressedThisFrame || keyboard.sKey.wasPressedThisFrame) Turn(Vector3.back);
if (keyboard.leftArrowKey.wasPressedThisFrame || keyboard.aKey.wasPressedThisFrame) Turn(Vector3.left);
if (keyboard.rightArrowKey.wasPressedThisFrame || keyboard.dKey.wasPressedThisFrame) Turn(Vector3.right);
}
timer += Time.deltaTime;
if (timer >= tick)
{
timer -= tick;
Step();
}
}
void Turn(Vector3 newDirection)
{
if (newDirection != -direction)
{
nextDirection = newDirection;
}
}
void Step()
{
direction = nextDirection;
Vector3 next = transform.position + direction;
if (Mathf.Abs(next.x) > edge || Mathf.Abs(next.z) > edge)
{
Die();
return;
}
transform.position = next;
if (GameManager.Instance.IsFood(next))
{
GameManager.Instance.Eat();
}
}
void Die()
{
alive = false;
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.