所以,事情是这样的。
我目前正在开发 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
方法时发生崩溃。
这是线程外观。
这是崩溃的那行。
最佳答案
您似乎使用 mainPlayer1.playerActive 作为信号量来阻止检查 keepUpdatingScore 方法中删除的 checkCollisionWithObstacle 循环(它们是异步的吗?)。假设它们是这样,如果代码在 checkCollisionWithObstacle 中开始循环后进入 keepUpdatingScore ,则阻止循环访问的方式将不起作用...您的里程将会有所不同。
关于iphone - 由于从 NSMutableArray 中删除 CCSprite 等元素而导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12841691/