I am struggling getting my head around NSMutableArrays and need some help.
I am trying to test the collisions of the ‘player’ and ‘coins’ littered through the level, ala traditional mario.
I am getting a crash reporting ‘* Collection <__NSArrayM: 0x4bf6d0> was mutated while being enumerated.’
I had followed a similar sprite collision method as per:
http://geekanddad.wordpress.com/2010/06/22/enemies-and-combat-how-to-make-a-tile-based-game-with-cocos2d-part-3/
For some reason if only 1 coin is spawned it all works fine – however if > 1 coin is spawned any coin-collision will throw the crash.
I understand this is a noob issue, and relates to [delete addObject:nuCoin]; – i have looked around and read making a sub array to handle the remove function – however im clearly lost and would appreciate the help, thanks in advance!
-(void) coinCollision {
NSMutableArray *coinsToDelete = [[NSMutableArray alloc] init];
NSMutableArray *delete = [[NSMutableArray alloc] init];
for (CCSprite *nuCoin in _coins) {
CGRect coinRect = CGRectMake((nuCoin.position.x+1) - (nuCoin.contentSize.width/4),
(nuCoin.position.y+5) - (nuCoin.contentSize.height/4),
nuCoin.contentSize.width/3.5,
nuCoin.contentSize.height/7);
for (CCSprite *Player in _player) {
CGRect playerRect = CGRectMake(player.position.x - (player.contentSize.width/4),
player.position.y - (player.contentSize.height*.05),
player.contentSize.width*.05,
player.contentSize.height/2);
if (CGRectIntersectsRect(coinRect, playerRect)) {
[coinsToDelete addObject:nuCoin];}
}
for (CCSprite *nuCoin in coinsToDelete) {
[[SimpleAudioEngine sharedEngine] playEffect:@"Coin.mp3"];
[_coins removeObject:nuCoin];
[delete addObject:nuCoin];
[map removeChild:nuCoin cleanup:YES];
}
}
[delete release];
}
You can’t add or remove objects to/from mutable arrays inside a fast enumeration
for(...in...)loop. You’ll need to develop some othe logic to make this work (e. g. store the indices of the objects to be deleted, or otherwise mark them as deletable and after finishing the for loop, delete all of them in one step.)Example: