I'm trying to implement the Simple Room Placement in Unity, but I have some trouble. When I hit the Play button Unity crashes. There is my code, the width and height are 172x80. Thanks for the help.
void GenerateRoom() {
int paddingX = 14;
int paddingY = 14;
roomX1 = Random.Range(0, width - paddingX);
roomY1 = Random.Range(0, height - paddingY);
roomX2 = Random.Range(roomX1 6, roomX1 paddingX);
roomY2 = Random.Range(roomY1 6, roomY1 paddingY);
for (int x = roomX1; x < roomX2; x ) {
for (int y = roomY1; y < roomY2; y ) {
if (map[x, y] == 0) {
GenerateRoom();
} else {
map[x, y] = 0;
}
}
}
}
Edit: If i change my code here:
for (int x = roomX1; x < roomX2; x ) {
for (int y = roomY1; y < roomY2; y ) {
if (map[x, y] != 0) {
map[x,y] = 0
}
}
}
Unity don't crash, so I presume that the problem is the recursion of the GenerateRoom() function. But in this way a room could be generate inside another room. How can I dodge that?
CodePudding user response:
Basicaly if you remove all the unnecessary things your code looks like that right now. You invoke GenerateRoom multiple times each time you invoke GenerateRoom, thats a fork-bomb. Maybe change value of map[x,y] to something else before invoking it again, it will stop crashing but still your recursion is quite weird GenerateRoom would be called for each cell I would rethink that.
GenerateRoom()
{
for (int x = 0; x < 100; x ) {
for (int y = 0; y < 100; y ) {
if(map[x,y] == 0){
//put something like map[x,y] = 1; here?
GenerateRoom();
}
}
}
}
CodePudding user response:
Ok, I have fix it. How suggested by Paweł Łęgowski I have change the code for don't check every tile if it's 0. I pick the 4 angle and check only theses points. Here it's the code:
void GenerateRoom() {
int paddingX = 14;
int paddingY = 14;
roomX1 = Random.Range(0, width - paddingX);
roomY1 = Random.Range(0, height - paddingY);
roomX2 = Random.Range(roomX1 6, roomX1 paddingX);
roomY2 = Random.Range(roomY1 6, roomY1 paddingY);
if (map[roomX1,roomY1] == 0 || map[roomX2, roomY2] == 0 || map[roomX2, roomY1] == 0 || map[roomX1, roomY2] == 0) {
GenerateRoom();
} else {
for (int x = roomX1; x < roomX2; x ) {
for (int y = roomY1; y < roomY2; y ) {
map [x, y] = 0;
}
}
}
}
Thanks for the help!