I’m working on a dungeon generator that generates rooms based on certain rules.
Whenever a room generates, I add its position to a list and make sure that the next room generated doesn’t generate at any of the coordinates in the list.
However, there are some instances where rooms still generate in an occupied spot. I’m a bit confused on why this is, as I tried my best to include as many “failsafes” as I could.
My code is attached below, and as always, thanks in advance for any help you may have!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DungeonGenerationManager : MonoBehaviour
{
public GameObject room_prefab;
public int numberOfRooms;
public int roomSize;
private void Start()
{
InitialIteration();
}
void InitialIteration() //Create rooms
{
List<Vector3> occupiedCoordinates = new List<Vector3>();
Vector3 currentPosition = Vector3.zero;
for(int i = 0; i < numberOfRooms; i++)
{
List<string> generationOptions = new List<string>();
if (!occupiedCoordinates.Contains(new Vector3(currentPosition.x + roomSize, 0,currentPosition.z)))
{
if (!generationOptions.Contains("right"))
{
generationOptions.Add("right");
}
}
if (!occupiedCoordinates.Contains(new Vector3(currentPosition.x - roomSize, 0, currentPosition.z)))
{
if (!generationOptions.Contains("left"))
{
generationOptions.Add("left");
}
}
if (!occupiedCoordinates.Contains(new Vector3(currentPosition.x, 0, currentPosition.z + roomSize)))
{
if (!generationOptions.Contains("up"))
{
generationOptions.Add("up");
}
}
if (!occupiedCoordinates.Contains(new Vector3(currentPosition.x, 0, currentPosition.z - roomSize)))
{
if (!generationOptions.Contains("down"))
{
generationOptions.Add("dowm");
}
}
string direction = generationOptions[Random.Range(0, generationOptions.Count)];
if(direction == "right")
{
currentPosition = new Vector3(currentPosition.x + roomSize, 0, currentPosition.z);
}
else if(direction == "left")
{
currentPosition = new Vector3(currentPosition.x - roomSize, 0, currentPosition.z);
}
else if(direction == "up")
{
currentPosition = new Vector3(currentPosition.x, 0, currentPosition.z + roomSize);
}
else if(direction == "down")
{
currentPosition = new Vector3(currentPosition.x, 0, currentPosition.z - roomSize);
}
occupiedCoordinates.Add(currentPosition);
Instantiate(room_prefab, currentPosition, Quaternion.identity);
}
}
}