Quest: Mining Quest

Challenge: Keep Your Enemies Clo…Farther

Feel free to share your solutions, ideas and creations below. If you get stuck, you can find some ideas here for completing this challenge.

Quest: Mining Quest

Challenge: Keep Your Enemies Clo…Farther

Feel free to share your solutions, ideas and creations below. If you get stuck, you can find some ideas here for completing this challenge.

Making progress on the challenges. This one took me a while.

There is probably a simpler solution, but it is working.

In Start() I calculate the player starting position (center). This will be needed, once the map size gets variable too.

```
private int centerLocationX;
private int centerLocationY;
void Start()
{
centerLocationX = (xSize / 2); // integer division
centerLocationY = (ySize / 2);
}
```

In SpawnEnemies() I start by calculating a List of valid locations (each an array with coordinates). If at least one coordinate x/y is not in the safe zone, the location is valid. Later I pick a random location from that list for each enemy.

```
private void SpawnEnemies()
{
// Challenge 5, safe space 3x3 around player
List<int[]> validLocations = new List<int[]>();
for (int x = 0; x < xSize; x++)
{
for (int y = 0; y < ySize; y++)
{
if (x < centerLocationX - 1 || x > centerLocationX + 1 ||
y < centerLocationY - 1 || y > centerLocationY + 1)
{
int[] location = { x, y };
validLocations.Add(location);
}
}
}
for (int i = 0; i < amountOfEnemies; i++)
{
int[] randomLocation = validLocations[Random.Range(0, validLocations.Count - 1)];
Vector2 spawnLocation = new Vector2(randomLocation[0], randomLocation[1]);
Instantiate(enemyPrefab, spawnLocation, Quaternion.identity);
}
}
```

2 Likes