Question

The app will crash when two sprites are touched at the same time.

-(void)addEnemy
{
  enemy = [CCSprite spriteWithFile:@"enemy.png"];
  enemy.position = ccp(winsize.width / 2,  winsize.height / 2);
  [spriteSheet addChild:enemy];
  [spritetiles addObject:enemy]; //spritetiles is NSMutableArray
}

touch code

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

if I touch any one of the sprite, there's no error, but if i touch two sprites(sometime some sprites' position is nearby), the app will crash, at the code line "if (CGRectContainsPoint(target.boundingBox, location)) {", so how can I fix it? thanks

Was it helpful?

Solution

Updated

Use reverseEnumerator in order to iterate through an array when you may need to remove elements as part of the for loop:

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [self convertTouchToNodeSpace: touch];

    for (CCSprite *target in [spriteSheet.children reverseObjectEnumerator]) {
        if (CGRectContainsPoint(target.boundingBox, location)) {
            [target stopAllActions];
            [spriteSheet removeChild:target cleanup:YES];
            [spritetiles removeObject:target];
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top