- Home /
How to prevent overlapping GameObjects before instantiation
I have created a basic 2D dungeon generator script that lays down rooms in a random offset direction from the last placed room. I am struggling to come up with a way to check if there is already a room spawned in the place where a new room will spawn. Right now the rooms will go back on themselves and create large blobs of overlapping rooms, like this example with 2000 rooms generated:
I have looked into different options on implementing some sort of ray casting solution where before I spawn the room I shoot a ray in the direction to check if there is a pre-existing room there and if there is it will choose a new direction. I confused of how I would implement this and any help would be appreciated. Here is the code that I am working with:
using UnityEngine;
using System.Collections;
public class Generator : MonoBehaviour {
//set up Gm's for generation
public GameObject roomBlock;
GameObject room;
//set the number of rooms that will spawn in total
public int numRooms = 8;
float posx, posy, posz = 0;
int randDirection;
Quaternion rotation = Quaternion.Euler(270, 0, 0);
void Start()
{
//Generation should only run through once at the start
Generate(numRooms, roomBlock);
}
void Generate(int nrms, GameObject roomBlock)
{
//create the starting room at coords 0,0,0
room = (GameObject)Instantiate(roomBlock, new Vector3(posx, posy, posz), rotation);
//subtract 1 room from room pool
nrms--;
for (int i = 0; i < nrms; i++)
{
//get xyz of last spawned room
posx = room.transform.position.x;
posy = room.transform.position.y;
posz = room.transform.position.z;
//choose random direction (NSEW)
randDirection = Random.Range(0, 4);
//based on randomized direction spawn a room
//spawn room in same position as last room but offset by 1 in the randomized direction
if (randDirection == 0)
{
room = (GameObject)Instantiate(roomBlock, new Vector3(posx + 1, posy, posz), rotation);
}
else if (randDirection == 1)
{
room = (GameObject)Instantiate(roomBlock, new Vector3(posx, posy + 1, posz), rotation);
}
else if (randDirection == 2)
{
room = (GameObject)Instantiate(roomBlock, new Vector3(posx - 1, posy, posz), rotation);
}
else if (randDirection == 3)
{
room = (GameObject)Instantiate(roomBlock, new Vector3(posx, posy - 1, posz), rotation);
}
}
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Get a tile relative to its position in the world 1 Answer
Physics2D Mesh Collider? 1 Answer