0
votes

I use following code to create some sprites

-(void)dologic
{

 for (int i = 0; i < 3; i ++) {
    CCSprite *target = [CCSprite spriteWithFile:@"pig.png"];
    int x = arc4random() % 320;
    int y = arc4random() % 300;
    target.position = ccp(x, y);
    [self addChild:target];
    [_targets addObject:target];//_targets is nsmutablearray
 }
}


- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
  UITouch *touch = [touches anyObject];
  CGPoint location = [self convertTouchToNodeSpace: touch];
  for (CCSprite *target in _targets) {
    if (CGRectContainsPoint(target.boundingBox, location)) {
        [_targets removeAllObjects];
        [self removeChild:target cleanup:YES];
        [self dologic];
    }
}

when touch any sprite, all sprites will be removed from the self first, and then call dologic to create three new sprites again, but my code can only remove the target that i touched, how can i remove all sprites when i touch the screen?

2

2 Answers

0
votes

First off, you are modifying the array while iterating it, which is not a good practice.

If you want to remove all targets upon touching any of them, you can try this:

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint location = [self convertTouchToNodeSpace: touch];
    BOOL touchedASprite = NO;
    for (int i = 0; i < [_targets count] && !touchedASprite; ++i) {
        if (CGRectContainsPoint((CCSprite*)[_targets objectAtIndex:i].boundingBox, location)) {
            touchedASprite = YES;
        }
    }
    if (touchedASprite) {
        for (CCSprite *target in _targets) {
            [self removeChild:target cleanup:YES];
        }
        [_targets removeAllObjects];
        [self doLogic];
    }
}
0
votes

When you want to remove objects in a array while browsing all objects of it, you should do like this:

for (int i = (int)_targets.count - 1 ; i >= 0 ; i--) {
    CCSprite *target = _targets[i];
    if (CGRectContainsPoint(target.boundingBox, location)) {
        [_targets removeAllObjects];
        [self removeChild:target cleanup:YES];
        [self dologic];
    }
}

Be careful: [NSArray count] returns a unsigned number, when [NSArray count] returns 0, ([NSArray count]-1) is NOT -1, should cast it to int