In an app I give random frames to squares every time it is run. I use this logic to make sure
a) each square is not too close to the player
and
b) each square is contained inside the view of the screen
c) no square touches any other square
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);
}
With this code, I would expect that each square in squareArray would be (once the loop was complete) completely inside the boundaries of the view, not intersecting with any other of the buttons in the array, and completely outside the boundaries of the playerRect rect, which is a square 120 x 120 in the center of the screen. Is my code wrong? Because I get none of these functionalities.
Edit: I do in fact get one of the desired traits of this method: no square ever intersects playerRect. But I still get squares overlapping each other and squares that are partially out of the view.
Edit 2:
I have made these changes to the nested for loop:
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;
}
And now the squares always are within the slightly modified (smaller) rect for the view, and they never intersect the player square. Yay. But they still appear on top of each other. Why?
In the end, this worked: (a combination of the wonderful answers of Rob Lourens and rob mayoff- thanks guys, and here, each of you have an upvote! 🙂 )