1

当同时触摸两个精灵时,应用程序将崩溃。

-(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
}

触摸码

-(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 (CGRectContainsPoint(target.boundingBox, location)) 处崩溃{",那么我该如何解决呢?谢谢

4

1 回答 1

2

更新

当您可能需要在 for 循环中删除元素时,请使用 reverseEnumerator 遍历数组:

-(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];
        }
    }
}
于 2013-10-25T03:51:17.977 回答