Eat
Lesson 6 of 14 in Coddy's Unity Game: Snake 3D course.
The snake eats when its head steps onto the food's cell. Both stand on whole numbers, so comparing their positions with == is safe: Unity's == on Vector3 counts two positions as equal when they are closer than 0.00001, and adding whole cells never leaves a gap that small.
The snake knows when it steps; the GameManager knows where the food is and keeps the score. So after each step the snake asks, and the GameManager answers: IsFood(cell) returns a bool, and Eat() adds a point and moves the food. The snake reaches the GameManager through a static Instance, the singleton you met in the C# for Unity journey.
Ask about the cell the head has entered, after the move. A key on a grid is picked up the same way:
transform.position = next;
if (key.position == transform.position)
{
keysHeld++;
key.gameObject.SetActive(false);
}Challenge
MediumIn GameManager:
- Add
public static GameManager Instance;, set it inAwake(), and addprivate int score;. - Write
public bool IsFood(Vector3 cell): true whencellis the food's position. - Write
public void Eat(): add 1 toscoreand callMoveFood().
In Snake, at the end of Step(), after the head has moved: if the head's cell is food, call Eat().
Press Play and steer onto the food, then press Check.
Try it yourself
using UnityEngine;
public class GameManager : MonoBehaviour
{
public Snake snake;
public GameObject foodPrefab;
private Transform food;
void Start()
{
food = Instantiate(foodPrefab).transform;
MoveFood();
}
void MoveFood()
{
int x = Random.Range(-snake.edge, snake.edge + 1);
int z = Random.Range(-snake.edge, snake.edge + 1);
food.position = new Vector3(x, 0f, z);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.