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?
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();
}
}
}
}
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 side I another function and check only theses points. Here it's the code:
void FindASpot() {
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);
bool xOK = true;
bool yOK = true;
for (int x = roomX1; x < roomX2; x++) {
if (map[x,roomY1] == 0 || map[x,roomY2] == 0) {
xOK = false;
}
}
for (int y = roomY1; y < roomY2; y++) {
if (map[roomX1,y] == 0 || map[roomX2,y] == 0) {
yOK = false;
}
}
if (xOK == true && yOK == true) {
GenerateRoom();
} else {
FindASpot();
}
}
void GenerateRoom() {
for (int x = roomX1; x < roomX2; x++) {
for (int y = roomY1; y < roomY2; y ++) {
map [x, y] = 0;
}
}
}
Thanks for the help!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.