RickON
RickON

Reputation: 395

Testing Rectagles Intersection on CGRect's

I am trying to detect collision between sprites from the same NSMutableArray. I am running a loop to compare one sprite with all of them, inclusing itself.

The thing is that the "CGRectEqualToRect" method is returning me a TRUE boolean, even though it is not!

- (BOOL)detectCollision: (CCSprite*)sprite{

BOOL result = FALSE;

CCSprite *toCollide;
CGRect rect1 = [GameScene positionRect:sprite];

for (int i = 0; i < [movableSprites count]; i++){

    toCollide = [movableSprites objectAtIndex:i];
    CGRect rect2 = [GameScene positionRect:toCollide];

    if (!CGRectIsNull(CGRectIntersection(rect1, rect2))) {
        if(!CGRectEqualToRect(rect1, rect2)){

          //handle collision
          NSLog(@"Collides");
          result = TRUE;
        }
    }

}

return result;

}

For instance, when debugging, rect1 is returning the same sizes as rect2, but its x and y are completely different.

Any ideas on this one?

Thanks!

Upvotes: 0

Views: 81

Answers (1)

Vivek Bansal
Vivek Bansal

Reputation: 1326

Try this..

   - (BOOL)detectCollision: (CCSprite*)sprite
    {
        BOOL result = FALSE;

        for (int i = 0; i < [movableSprites count]; i++)
        {
            CCSprite *toCollide; = [movableSprites objectAtIndex:i];
            if(sprite==toCollide){
                continue;
            }
            if (CGRectIntersectsRect(sprite.boundingBox, toCollide.boundingBox)) {

                //handle collision
                NSLog(@"Collides");
                result = TRUE;
                return result;
            }

        }
      return result;
    }

Make sure that all sprites are added to same object(Parent),otherwise you same to do some changes..

Upvotes: 1

Related Questions