【问题标题】:Proper garbage collect for bullets正确收集子弹的垃圾
【发布时间】:2013-09-21 20:13:16
【问题描述】:

所以我正在为我正在开发的游戏使用简单的子弹系统,但我想知道从阵列和屏幕中移除子弹的最佳方法是什么,这样它就不会占用帧速率和内存?

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

[bullets removeObject:bullet] 会导致应用程序在一颗子弹击中瓷砖而另一颗子弹在屏幕上时崩溃(我认为是问题所在)。那么什么才是正确的去除子弹的方法呢?

【问题讨论】:

    标签: iphone xcode cocos2d-iphone


    【解决方案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];
    }
    

    【讨论】:

    • 它是说子弹是一个未声明的标识符,这是有道理的,因为我没有在 bulletsToRemove 的任何地方声明它。我应该在哪里申报?
    • 对不起,编辑了我的答案!在第二个循环中,我的变量名错误。
    • 你也可以使用 [bullets removeObjectsInArray:bulletsToRemove];
    • 这更有意义!但是,它一运行就崩溃并突出显示 bulletsToRemove for 循环作为原因?
    • 使用 [bullets reverseObjectEnumerator] 然后你可以删除枚举的对象。这也会更快,因为 removeObject: 会再次枚举数组,直到找到要删除的对象。
    猜你喜欢
    • 2012-05-15
    • 2011-08-04
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    相关资源
    最近更新 更多