1

2 つのスプライトが同時にタッチされると、アプリがクラッシュします。

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

スプライトのいずれかをタッチするとエラーは発生しませんが、2 つのスプライトをタッチすると (いくつかのスプライトの位置が近くにある場合があります)、アプリがクラッシュし、コード行で "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 に答える