2

所以,事情是这样的。

我目前正在开发 Cocos2d 游戏,它包含许多障碍。像这样每隔 10 秒在屏幕上添加一个障碍物。

ObstacleSprite* newObstacle = [ObstacleSprite spriteWithFile:@"Obstacle.png" rect:CGRectMake(0, 0, 20, 20)];
            newObstacle.position = ccp(mainPlayer1.position.x,10);
[self addChild:newObstacle];

[self.arrayForObstacles addObject:newObstacle];

现在,我将这些障碍物插入到 中,arrayForObstacles因为我还想继续检查 Obstacles 和 MainPlayer 是否没有碰撞。

我在这个函数的帮助下检查它。

- (void) checkCollisionWithObstacle
{
    if(mainPlayer1.playerActive)
    {
        for(int  i = 0; i < [self.arrayForObstacles count]; i++)
        {
            ObstacleSprite* newObstacle = [self.arrayForObstacles objectAtIndex:i];
            if(newObstacle != nil)
            {
                if(CGRectIntersectsRect([mainPlayer1 boundingBox], [newObstacle boundingBox]))
                {
                    mainPlayer1.livesLeft--;
                }
            }
        }
    }
}

问题

问题是当我达到某个分数时,其中一个障碍被删除。排除障碍的工作方式与先进先出 (FIFO) 模式相同。因此,要删除障碍,我编写了以下方法:

- (void) keepUpdatingScore
{
    //update new score
    mainPlayer1.score+=10;
    //remove obstacle when score increases by 5k
    if(mainPlayer1.score > 5000 && mainPlayer1.score > 0)
    {        
        mainPlayer1.playerActive = NO;

        if([self.arrayForObstacles count] > 0)
        {            
            CCLOG(@"count is %d",[self.arrayForObstacles count]);
            ObstacleSprite* newObstacle = [self.arrayForObstacles objectAtIndex:0];
            [self.arrayForObstacles removeObjectAtIndex:0];
            [self removeChild:newObstacle cleanup:YES];

            CCLOG(@"count is %d",[self.arrayForObstacles count]);
        }

        mainPlayer1.playerActive = YES;

    }    
    else
    {

    }

当分数超过5000分时它崩溃了!

更新

当它再次进入方法时会发生崩溃checkCollisionWithObstacle

这是线程外观。

在此处输入图像描述

这是崩溃的行。

在此处输入图像描述

4

1 回答 1

2

您似乎正在使用 mainPlayer1.playerActive 作为信号量来阻止检查 checkCollisionWithObstacle 循环从 keepUpdatingScore 方法中的删除(它们是异步的吗?)。假设它们是,如果代码在 checkCollisionWithObstacle 中开始循环之后进入 keepUpdatingScore ,则阻止循环访问的方式将不起作用......您的里程会有所不同。

于 2012-10-11T15:18:05.267 回答