布尔值+ while循环=
本文关键字:循环 while 布尔值 | 更新日期: 2023-09-27 17:49:16
我对下面的代码有一个奇怪的问题(我已经剥离了不相关的部分,并且引用的任何类/函数都按预期工作):
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++;
}
}
由于某种原因,failed的计算结果总是为true。我抛出了几个调试消息,奇怪的是,计算失败了两次——第一次,在foreach循环中,它的计算是正确的。第二次,它的计算结果为false。如果我将failed初始化为true,那么第二次它的计算结果为true,几乎就像while循环运行了两次,第二次忽略了foreach循环。
为什么会这样?
编辑1:这是我的矩形类和相关变量:
public class Rectangle {
public int x1;
public int y1;
public int x2;
public int y2;
public bool Intersect(Rectangle other) {
return (x1 <= other.x2 && x2 >= other.x1 && y1 <= other.y2 && y2 <= other.y1);
}
public Rectangle(int x, int y, int w, int h) {
this.x1 = x;
this.x2 = x+w;
this.y1 = y;
this.y2 = y + h;
}
public Rectangle() {
}
public Vector2 Center() {
int centerX = (x1 + x2) / 2;
int centerY = (y1 + y2) / 2;
Vector2 center = new Vector2(centerX, centerY);
return center;
}
}
下面是我使用的变量:
public Vector2 levelSize = new Vector2(80,30);
public int maximumRoomSize = 10;
public int minimumRoomSize = 5;
你的数学错了。:
public bool Intersect(Rectangle other) {
return (x1 <= other.x2 && x2 >= other.x1 && y1 <= other.y2 && y2 <= other.y1);
}
应该更改为(注意我在语句的后半部分将<=
更改为>=
):
public bool Intersect(Rectangle other) {
return (x1 <= other.x2 && x2 >= other.x1 && y1 <= other.y2 && y2 >= other.y1);
}
我不是很肯定,但是你对矩形的使用。机密数据库可能不对。Intersect返回一个表示两个指定矩形相交的矩形,如果没有相交,则返回一个"空"矩形。你可以试试IntersectsWith——它返回一个布尔值。
似乎没有任何错误与你的循环逻辑,将设置failed
不正确。如果您确信该方法不会在第二个循环中失败,请检查您的辅助方法,特别是Rectangle.Intersect
。添加更多的跟踪输出对调试也很有用。
在每次while循环的迭代中,failed被重新初始化为false
我对两次评估感到困惑?当然,在break之后,它退出for循环。也许尝试清理您的解决方案,删除隐藏的obj目录,然后重新构建?
在不了解Intersect方法的情况下,我会说这一定是导致你的问题的原因。你说while循环的第一次迭代(猜我的部分-你的问题是模糊的部分)给出了失败的正确评估(我猜这是在if (!failed)
行)。这里没有调用Intersect方法,因为rooms数组中没有房间,因此从failed变量的初始化中得到failed为false。然后在第二次通过while循环时,在rooms数组中有一个房间,Intersect方法对您的目的进行了不正确的评估,并且总是说有一个交叉点。我现在可以看到@FreeAsInBeer在Intersect方法中看到了一个错误。