适当的垃圾收集子弹

时间:2013-09-21 20:13:16

标签: iphone xcode cocos2d-iphone

所以我正在使用一个简单的子弹系统来处理我正在进行的游戏,但我想知道从阵列和屏幕中移除子弹的最佳方法是什么,以免它占用帧速率和内存?

-(void)spinTapped
{     
        [self.character stopAllActions];
        [self.character runAction:self.gunAction];
        isRunning = NO;
        CCSprite *bullet = [CCSprite spriteWithFile:@"rwby_bullet.png"];
        bullet.position = ccp(self.character.position.x , self.character.position.y + 15);
        [bullet setScale:2];
        if (isRight) {
            bullet.tag = 10;
        }
        else {
            bullet.tag = -10;
        }
        [bullets addObject:bullet];
        [self addChild:bullet z:-1];

}

然后在更新中:

for(CCSprite *bullet in bullets)
    {
        CGPoint bulletPosition = ccp(bullet.position.x , bullet.position.y);
        CGPoint B_tilePosition = [self tileCoorForPosition:bulletPosition];
        bullet.position = ccp(bullet.position.x + bullet.tag , bullet.position.y);

        NSMutableArray *emptySpace = [[NSMutableArray alloc] initWithCapacity:10000];
        [emptySpace addObject:[NSNumber numberWithInt:0]];

        @try {
            bullet_GID = [self.background tileGIDAt:B_tilePosition];
        }
        @catch (NSException *exception) {
            bullet_GID = 535677655;
        }
        @finally {

        }
        if(bullet_GID == 535677655)
        {
            [bullet setVisible:NO];
          //  [bullets removeObject:bullet];

        }
        else if(bullet_GID)
        {
            [bullet setVisible:NO];
          //  [bullets removeObject:bullet];
        }
    }

[bulletlets removeObject:bullet]导致应用程序在一个项目符号触及一个项目符号而另一个项目符号出现在屏幕上时崩溃(这是我认为问题所在)。那么删除子弹的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

崩溃可能是因为你试图在重复数组时从子弹阵列中删除你的子弹对象':在迭代时不能修改数组。所以,我建议你做一些像

这样的事情
NSMutableArray *bulletsToRemove = [NSMutableArray array];

for (CCSprite *bullet in bullets) {
   // your logic 
   if('should remove bullet') {
       [bulletsToRemove addObject:bullet];
   }
}

// now iterate the bullets to remove array, and remove safely from
// the bullets array

for (CCSprite *bulletToRemove in bulletsToRemove) {
    [bullets removeObject:bulletToRemove];
}