- Home /
Optimising code for spawning food in snake game
I'm making a snake game and need to prevent the food from spawning inside the snake or the walls of the map (there are also walls inside the map). I am currently achieving this by creating a list of all the possible coordinates for a food object to spawn in whenever the snake eats a food item and a new one must be spawned. This seems to be very inefficient as I get a huge frame drop whenever food is spawned. I was wondering if there is a better way to find a location that does not collide with the snake or the walls. Any help would be very much appreciated :)
Some other info on my game for context: the spawning of food and the location of the snake is quantized to 10 coordinate divisions. This allows smooth movement of the snake however the snake is always part of a rigid 12 by 10 grid.
public GameObject foodPrefab;
public Transform borderTop;
public Transform borderBottom;
public Transform borderLeft;
public Transform borderRight;
// Use this for initialization
void Start () {
Spawn ();
}
public void Spawn () {
List<Vector2> spawn_locations = new List<Vector2>();
for (int x = -120; x < 120; x = x + 10) {
for (int y = -100; y < 100; y = y + 10) {
if (Physics2D.OverlapCircle(new Vector2(x, y), 0.5f) == false) {
spawn_locations.Add (new Vector2 (x, y));
}
}
}
Vector2 coords = spawn_locations[Random.Range(0, spawn_locations.Count)];
Instantiate (foodPrefab, new Vector3(coords.x, coords.y, 0), Quaternion.identity);
}
Answer by toddisarockstar · Nov 24, 2018 at 05:27 PM
the OverlapCircle is slowing you down when you are calling it 480 times!!!!! a better approach would be: choose and random space, call the overlap once. if it is clear, you are done.
if not.... simple choose another random till you get a clear space. instead of doing 480 checks this should give you the same effect and you should be doing just a couple checks per spawn!!!!!!
the loop in this function repeats till it gets a good spot
public void Spawn () {
int checks = 0;
int x = 0; int y=0;
while (checks <5000) {
checks++;
// get random coordinate between -120 and + 120.
x = Random.Range (0, 25) - 12;x *= 10;
y = Random.Range (0, 21) - 10;y *= 10;
if(!Physics2D.OverlapCircle(new Vector2(x, y), 0.5f)){break;}
}
Instantiate (foodPrefab, new Vector3(x, y, 0), Quaternion.identity);
print("I checked " + checks + " places before i found a spot");
}