【发布时间】:2011-11-20 01:40:49
【问题描述】:
在一个应用程序中,我每次运行时都会给正方形随机帧。我用这个逻辑来确保
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;
}
现在方块总是在视图的略微修改(更小)的矩形内,并且它们永远不会与玩家方块相交。耶。但它们仍然出现在彼此之上。为什么?
【问题讨论】:
-
您没有提出问题或解释您认为代码有什么问题。
-
Bahahaha 对不起,我在实际提问之前不小心发布了它,因为我很着急。正在更新中...
标签: objective-c cocoa-touch cgrect