Search code examples
iphoneobjective-cioscocos2d-iphoneccsprite

cocos2d CCSprite Collision issue


[I have 2 objects, both of them subclass of CCSprite. Each one of them has a CCSprite variable that actually represents the sprite image

Example:

@interface Player : CCSprite
{
    CCSprite *sprite;
}

@property (nonatomic, retain) CCSprite *sprite;

I'm trying to detect collision of the both but when I try:

- (void)detectCollision:(id)sender
{    
    for (Player *tempPlayer in self.playersArray) {        
        if (CGRectIntersectsRect([tempPlayer boundingBox], [mainPlayer boundingBox])) {
            //Collision
        }
    }
}

It doesn't recognize any collision, when I try:

- (void)detectCollision:(id)sender
{    
    for (Player *tempPlayer in self.playersArray) {        
        if (CGRectIntersectsRect([tempPlayer.sprite boundingBox], [mainPlayer.sprite boundingBox])) {
            //Collision
        }
    }
}

It detects collision when both objects are displayed on screen even if the haven't collided yet.

Edit: Forgot to add boundingBox to the objects...

Thanks


Solution

  • tempPlayer.sprite and mainPlayer.sprite bounding boxes will represent the rect in their own superview which is also a sprite, not the world. For example if the mainPlayer's rect is (150, 200, 100, 100), and the sprite inside it has the same rect, its boundingBox will be (0, 0, 100, 100).

    I once got this problem and solved it as follows: x for tempPlayer.sprite in world coordinates = x for tempPlayer + x for tempPlayer.sprite.

    and same thing for y.