游戏偶尔会在检查精灵时崩溃

时间:2014-04-15 18:35:58

标签: ios objective-c cocos2d-iphone

我的游戏一直在围绕这个特定的代码块崩溃。

错误消息为Thread1: EXC_Bad_ACCESS(code =1),突出显示的代码如下:

-(void)updateForArrays:(ccTime)delta
{
   for (CCSprite *child in [self children]){
        if (child.tag==2) {

            if (CGRectIntersectsRect(child.boundingBox, _ship.boundingBox)) {
                [self removeChild:child cleanup:YES];
                _score += 1;
                [_scoreLabel setString:[NSString stringWithFormat:@"Score : %d",_score]];
            }
        }if (child.tag ==3){
            if (CGRectIntersectsRect(child.boundingBox, _ship.boundingBox)) {
                CCScene *gameOverScene = [GameOverLayer gameOverScene];
                [[CCDirector sharedDirector] replaceScene:gameOverScene];

            }
        }
     }
}

2 个答案:

答案 0 :(得分:3)

迭代时不应修改([self removeChild:child cleanup:YES])集合([self children]数组)。解决此问题的一种方法是在单独的数组中添加要删除的对象,并在检查完碰撞后将其删除。

编辑:

NSMutableArray *cleanupArray = [NSMutableArray array];
for (CCSprite *child in [self children]) {
    // ...
    [cleanupArray addObject:child]; // instead of [self removeChild:child cleanup:YES];
    // ...
}

// actual removal of children
for (CCSprite *child in cleanupArray) {
     [self removeChild:child cleanup:YES];
}
[cleanupArray removeAllObjects];

答案 1 :(得分:0)

如果self的所有子节点都是CCSprite类型,那么您的代码将起作用。如果没有,那么你将面临崩溃。因为有可能强制类型化一个没有CCSprite类的子节点。看看这段代码是否有帮助

-(void)updateForArrays:(ccTime)delta
{
for (id item in [self children]){
    if((item isKindOfClass:(CCSprite class)])
    {
     CCSprite *child = (CCSprite *)item;
      if (child.tag==2) {

        if (CGRectIntersectsRect(child.boundingBox, _ship.boundingBox)) {
            [self removeChild:child cleanup:YES];
            _score += 1;
            [_scoreLabel setString:[NSString stringWithFormat:@"Score : %d",_score]];
        }
    }if (child.tag ==3){
        if (CGRectIntersectsRect(child.boundingBox, _ship.boundingBox)) {
            CCScene *gameOverScene = [GameOverLayer gameOverScene];
            [[CCDirector sharedDirector] replaceScene:gameOverScene];

        }
    }
   }
 }
 }
相关问题