Hello.
I'm rather new to serious programming, so please forgive my dumbness, but I've failed to figure this out by myself.
I am writing a game with cocos2d-iphone. I have a scene object with several NSMutableSets in its ivars - units, buildings, rockets, etc. I have a problem removing objects from these NSMutableSets. When a bullet object is init-ed it among other things searches for a target that it should damage like this:
...
for ( RXUnit * unit in targetSet ) {
if ( ccpDistance( unit.position, rayPoint ) < 20 ) {
...
[unit damageSelfBy:damage];
...
}
}
...
The [unit damageSelfBy:damage]
method kills the unit if it does not have enough HP to sustain damage. Among other things it does this:
[scene.units removeObject:self];
(scene.units is the same NSMutableSet as targetSet in the loop above)
Whenever this line is used, the bullet that was shot at the time the unit is being removed from the set fails to init properly. The bullet init method executes up to the for loop shown above (yes, the unit does get damaged and removed by previous bullet), but anything else that goes after this loop in the init method is just not executed.
Surprisingly, the application continues to run normally with no visible effects apart from that stuck bullet. Console does not show any warnings/errors, there are no warnings when compiling either.
I also tried delaying the time the unit is removed from the set by putting the actual removal code in the scene's update method, but that does not help.
I think I can make some ugly hacks to hide this problem, but I'm sure it will bite me in the ass later. And well, I would really like to understand what is going on and how to properly address it.
Any help/ideas are much appreciated. Maybe I shouldn't even store game objects in NSMutableSets?