在一个应用程序中,我每次运行时都会给正方形随机帧。我用这个逻辑来确保
a) 每个方格都不太靠近玩家
b) 每个方格都包含在屏幕视图内 c) 没有一个方格接触任何其他方格
for(UIButton* button in squareArray) {
BOOL shouldContinue = YES;
do {
int randX = arc4random() % 321;
int randY = arc4random() % 481;
button.frame = CGRectMake(randX, randY, button.frame.size.width, button.frame.size.height);
CGRect playerRect = CGRectMake(100, 180, 120, 120);
for(UIButton* b in squareArray)
if(!CGRectIntersectsRect(b.frame, button.frame) &&
!CGRectIntersectsRect(button.frame, playerRect) &&
CGRectContainsRect(self.view.frame, button.frame)) {
shouldContinue = NO;
}
} while (shouldContinue);
}
使用此代码,我希望 squareArray 中的每个正方形(一旦循环完成)将完全在视图的边界内,不与数组中的任何其他按钮相交,并且完全在 playerRect rect 的边界之外,即屏幕中央的一个 120 x 120 正方形。我的代码错了吗?因为我没有这些功能。
编辑:事实上,我确实得到了这种方法所需的特性之一:没有正方形与 playerRect 相交。但是我仍然得到相互重叠的正方形和部分不在视图中的正方形。
编辑2:
我对嵌套的 for 循环进行了这些更改:
for(UIButton* b in squareArray)
if(![b isEqual:button]) {
if(CGRectIntersectsRect(b.frame, button.frame) ||
CGRectIntersectsRect(button.frame, playerRect) ||
!CGRectContainsRect(CGRectMake(10, 10, 300, 460), button.frame))
shouldContinue = YES;
else
shouldContinue = NO;
}
现在方块总是在视图的略微修改(较小)的矩形内,并且它们永远不会与玩家方块相交。耶。但它们仍然出现在彼此之上。为什么?