循环遍历数组以移除触摸对象(iPhone/Cocos2d)



我使用cocos2d来创建游戏。我有一个CCSprites数组,我希望能够触摸它们并删除被触摸的一个。

现在我有这个…

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

我以前从来没有做过这个。有人有解决办法吗?

谢谢,迈克尔。

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

这段代码使用for-each来创建满足条件的对象数组,然后删除它们。

最新更新