Search code examples
cocos2d-iphonecollision-detectionccspritebounding-box

Cocos2D Simple Collision Detection of a sprite, children of another sprite


I have a problem in my collision detection (I'm using cocos2d, not box2D or Chipmunk). Basically, I have the Player, which is a CCSprite, and Projectiles, also CCSprite. Everything works fine thus far using CGRectIntersectRect, but in the game the player can activate a super laser of doom, which is always in front of the player. The way I included it is that I add it as a child of the player, so I don't have any more code to do about stuffs like rotation or moving. But the problem I have is that it doesn't detect collision with the projectiles correctly, since the laser's position is always 0,0 because it's added to the player and not the scene.

Here's my code :

Player.m

- (bool) activateSuper{
bool activated = NO;
if (powerReady) {
    NSLog(@"Super Activated!!!!!");
    activated = YES;
    _state = pSuper;

    //Super sprite which is supposed to collide with projectiles
    _sprSuper = [CCSprite spriteWithSpriteFrameName:@"Laser.png"];
    _sprSuper.anchorPoint = ccp(0.5, 0.0);
    _sprSuper.position = ccp(self.contentSize.width/2, self.contentSize.height);
    [self addChild:_sprSuper];

    //Delete
    int duration = 5;
    [self runAction:[CCSequence actionOne:[CCDelayTime actionWithDuration:duration]
                                      two:[CCCallBlock actionWithBlock:^{
        [self removeChild:_sprSuper cleanup:YES];
        powerReady = NO;
        curSuper = 0;
        _state = pOK;
    }]]];

    //Empty super bar
    GameScene *g = (GameScene*)[self parent];
    [g.gameHUD emptyBar:duration];
}

return activated;
}

In GameScene.m (For collision detection):

- (void) update:(ccTime)dt{
Projectile *pToRemove = nil;
for (Projectile *p in projectiles){

    if (player.state == pSuper && CGRectIntersectsRect(p.boundingBox, player.sprSuper.boundingBox)) {
        pToRemove = p;
        break;
    }
}

if (pToRemove != nil) [self destroyProjectile:pToRemove];

}

What do you think I should focus on? Is there an easy way of detecting the collision, or should I add the Laser in the scene and add code to make it move with the player?

Thank you really much for your answer!


Solution

  • you can try some things:

    1. play with the convertToWorldSpace and convertToNodeSpace from scene and player

    2. put the laser in the scene and when you move the player also move the laser

      • you can send a reference of the laser to the player and overriding the method setPosition() in the player

            -(void) setPosition(CGPoint newPos){
                    [laser setPosition:newPos];
                    [super setPosition:newPos];
            }        
        

        here, every time when you move the player(CCMoveTo, CCMoveBy, etc) the laser move too.

      • other option is when you move the player send the same action to the laser