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
MediumThe snake eats the food and scores a point.
- In
GameManager, addpublic static GameManager Instance;, set inAwake(), andprivate int score; public bool IsFood(Vector3 cell): true when cell is the food's position.public void Eat(): one more point, thenMoveFood().- In
Snake, at the end ofStep(): ifGameManager.Instance.IsFood(next), callEat().
Press Play and steer onto the food: it jumps to a new cell. Then 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);
}
}
All lessons in Unity Game: Snake 3D
Practice on your own: Unity playground