jahan
jahan

Reputation: 124

CGRect Grid on screen?

I want to create a grid of rectangles at the centre of screen leaving some space on the edges. The need of that arises because I am spewing different sprites at random points and they keep spawning on top of eat other. So i thought if there is a way of creating a class that creates the grid and returns me with a random rect and mark it occupied as long at the sprite stays in that rect and make it free after.

If i can get some help or any tips it will be great. Any other solutions to achieve this are welcome too.

Thanks.

Upvotes: 1

Views: 414

Answers (2)

jahan
jahan

Reputation: 124

Thanks @andrewx for your help. This will create CGRect in the given range and then return a random one.

-(void) makeCGRectArray{

rectsArray = [[NSMutableArray alloc] init];

for (int x = 30; x<=420; x= x+60) {
    for (int y=40; y<=280; y=y+40) {

        CGRect newRect = CGRectMake(x, y, 60, 40);
        [rectsArray addObject:[NSValue valueWithCGRect:newRect]];
    }
}

[self getRandomCgrect:rectsArray];

}

 -(CGRect) getRandomCgrect:(NSMutableArray*) rectArray{

    NSInteger randomPoint = (arc4random() % (49));

    CGRect randomRect = [[rectsArray objectAtIndex:randomPoint] CGRectValue];

    self.isOccupied = YES;
    return randomRect;
}

Upvotes: 0

johnbakers
johnbakers

Reputation: 24760

You could nest two for loops, one for rows and one for columns, make them both run 5 times, and in each loop increment the x position and y position by one-fifth the width and height of the screen and put these coordinates into a CGRrect. That would do what you want.

Upvotes: 1

Related Questions