Hi, I've got an odd issue with the below code (I've stripped out the parts that are irrelevant, and any classes/functions referenced are working as expected):
int curNumRooms = 0;
while(curNumRooms < numberOfRooms) {
int w = Random.Range(minimumRoomSize, maximumRoomSize+1);
int h = Random.Range(minimumRoomSize, maximumRoomSize+1);
int x = Random.Range(0, (int)levelSize.x - w - 1);
int y = Random.Range(0, (int)levelSize.y - h - 1);
Rectangle newRoom = new Rectangle(x,y,w,h);
bool failed = false;
foreach (Rectangle otherRoom in rooms) {
if(otherRoom != null) {
if (newRoom.Intersect(otherRoom)) {
failed = true;
break;
}
}
}
if (!failed) {
rooms[curNumRooms] = newRoom;
curNumRooms++;
}
}
For some reason, `failed` always evaluates to true. I threw in a couple debug messages, and for some reason, failed evaluates twice -- the first time, in the foreach loop, it evaluates correctly. The second time, it evaluates to false. If I initialize `failed` as true, then it evaluates to true the second time, almost as if the while loop was being run twice, and ignoring the foreach loop the second time around.
Why is this?
what if the random new room was intersecting another room? I bet random is really pseudo random. did you try changing the Random.seed?
– loopyllamaWell, the point is to avoid intersecting; if it does intersect, then set "failed" to true and don't create a room at that point. However, it's setting failed to true, then back to false for some reason, so rooms are being created overlapping, etc.
– e-bonnevilleIt looks ok, so if it is failing, then I would guess they are in fact intersecting and it will loop forever. Try outputting the coordinates. e.g. if levelSize is < w or h, all Rects would be at 0, 0.
– MolixActually, I just found it. It was an error in my Intersect function.
– e-bonneville