FreeFire
FreeFire

Reputation: 169

Better understanding of CGRect in cocos2d

I'm trying to expand my knowledge when using cocos2d and I have 2 questions : 1. What is CGRects purpose and 2. If its used to makes sprites collide, how do I do that?

Upvotes: 1

Views: 385

Answers (1)

Adrian P
Adrian P

Reputation: 6529

CGRect is a C struct, defined as part of Core Graphics (hence the CG), ie it’s a “data” container, nothing more, nothing less.

It’s actually made of two more C structs, a CGPoint for the origin and a CGSize for the size, as you no doubt realise.

In Core Graphics (Quartz) on the Mac, the coordinate system is bottom left defines the origin, also for OpenGL and hence Cocos2d. On iOS it’s top left. Where that origin is often depends on where you are in, for example, the view hierarchy (look at frame and bounds in the UIView documentation).

However, this makes no difference to CGRect, the struct is not enforcing a coordinate system, only defining a data type that has an origin and a size. It would work equally well for a coordinate system defined as rotated 45 degrees to that used on iOS – the expectation is that you are consistent in your use, of course

And to answer your second question, here is a sample code of collision detection.

NSMutableArray *projectilesToDelete = [[NSMutableArray alloc] init];
for (CCSprite *projectile in _projectiles) {

    NSMutableArray *monstersToDelete = [[NSMutableArray alloc] init];
    for (CCSprite *monster in _monsters) {

        if (CGRectIntersectsRect(projectile.boundingBox, monster.boundingBox)) {
            [monstersToDelete addObject:monster];
        }
    }

    for (CCSprite *monster in monstersToDelete) {
        [_monsters removeObject:monster];
        [self removeChild:monster cleanup:YES];
    }

    if (monstersToDelete.count > 0) {
        [projectilesToDelete addObject:projectile];
    }
    [monstersToDelete release];
}

for (CCSprite *projectile in projectilesToDelete) {
    [_projectiles removeObject:projectile];
    [self removeChild:projectile cleanup:YES];
}
[projectilesToDelete release];

And to better understand the whole concept, here is a link to a great tutorial by ray. http://www.raywenderlich.com/25736/how-to-make-a-simple-iphone-game-with-cocos2d-2-x-tutorial

Upvotes: 1

Related Questions