Search code examples
ioscocos2d-iphonecollision-detectionspritecgrect

Collision detection does not return anything


I am having some trouble with really quite simple collision detection. Here is my code that I am using at the moment:

- (void) update:(ccTime)dt{
NSLog(@"update");
if (CGRectIntersectsRect([self.sprite boundingBox], [self.swat boundingBox])) {
    NSLog(@"detected");
}}

'sprite' and 'swat' are subclassed CCSprites that have been declared as a property using:

@property (nonatomic, assign) CCSprite *swat;
@property (nonatomic, assign) enemyClass *sprite; //enemyClass is a subclass of CCSprite
//note that they have also been synthesized

Do I need to change the attributes to get the collision detection working?

I have also tried the following code:

This returns update only:

- (void) update:(ccTime)dt{
NSLog(@"update");
if (CGRectIntersectsRect(self.sprite.boundingBox, self.swat.boundingBox)) {
    NSLog(@"detected");
}}

This returns 'detected' over and over, even when they are not colliding:

- (void) update:(ccTime)dt{
NSLog(@"update");
if (CGRectIntersectsRect(self.sprite.textureRect, self.swat.textureRect)) {
    NSLog(@"detected");
}}

In both sets of code, 'update' is logged, so the update is working correctly, it is just the if statement that is giving me the problem.

If you could give me any solutions to why this isn't working, or any alternative ways to get it working, I'd be grateful. Thanks.


Solution

  • CGRectContainsRect returns true if second rectangle is contained in first. Are you sure you need "contains" check, not "intersects" (CGRectIntersectsRect) check?