objective-ccocos2d-iphonetouchremovechildccnode

How to remove a CCnode with a touch?


I need help I have tried to remove a ccnode that constantly is respawning at different locations and adding them to an array to get control of which sprites are on screen, but the thing is that I can't get to remove them. It detects the touches but doesn't get removed any ideas? Here is the code I'm using to get rid of the node.

 - (void)touchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{

CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToUI:location];
for (CCNode *sprite in _spritesOnScreen) {
if (CGPointEqualToPoint(sprite.position, location)) {
    [_spritesOnScreen removeObject:sprite];
    [self removeChild:sprite cleanup:YES];

}
 }
}

Solution

  • Allow me to offer you a slightly different approach. Subclass CCNode to CCAppleNode and within the CCAppleNode.m file detect touches and call removeFromParent on touchBegan. This way the CCAppleNode class is taking up the responsibility of removing itself from parent when its touched, taking away this responsibility from your main game scene.

    -(void) touchBegan:(UITouch *)touch withEvent:(UIEvent *)event{
        [self removeFromParentAndCleanup:YES];
        [super touchBegan:touch withEvent:event];
    }