Search code examples
iphonearrayscocos2d-iphoneccsprite

Looping through an array to remove a touched object (iPhone/Cocos2d)


I am using cocos2d to build a game. I have an array of CCSprites and I want to be able to touch them and delete the one that was touched.

Right now I have this...

-(void) spawn {
   mySprite = [CCSprite spriteWithFile:@"image.png"];
   mySprite.position = ccp(positionX,positionY);
   [myArray addObject:mySprite];
   [self addChild:mySprite];
}
- (void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
   UITouch* touch = [touches anyObject];
   CGPoint location = [touch locationInView: [touch view]]; 

    NSUInteger i, count = [myArray count];
    for (i = 0; i < count; i++) {
    mySprite = (CCSprite *)[myArray objectAtIndex:i];
    if (CGRectContainsPoint([mySprite boundingBox], location)) {

       [self removeChild:mySprite cleanup:YES]; 

    }
}

I have never done this before. Does anyone have a solution?

Thanks, Michael


Solution

  • - (void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch* touch = [touches anyObject];
        CGPoint location = [touch locationInView: [touch view]]; 
        NSMutableArray *spritesToDelete = [[NSMutableArray alloc] init];
    
        for(CCSprite* mySprite in myArray) {
            if (CGRectContainsPoint([mySprite boundingBox], location))
                [spritesToDelete addObject:mySprite];
    
        for(CCSprite* deadSprite in spritesToDelete) {
            [self removeChild:deadSprite cleanup:YES];
            [myArray removeObject:deadSprite];
        }
    }
    

    This code uses a for-each to create an array of the objects that meet your condition, and then removes them.