I'm trying to make a very simple collision detection procedure just for test purposes.
The problem is with the send/receive information between functions
I have these lines on the update method (could be later implemented for checking what kind of subclass node is)
CCSprite *sprite = [background spriteCollisionWithRect:player.boundingBox];
if (sprite!=nil) {
[sprite removeFromParentAndCleanup:YES];
}
and this is the spriteCollisionWithRect method
-(CCSprite*)spriteCollisionWithRect:(CGRect)bounds
{
for (CCSprite *sprite in _spritesArray) {
if (CGRectIntersectsRect(sprite.boundingBox, bounds)) {
return sprite;
}
}
return nil;
}
Now, this way not all the sprites are removed. It only works occasionally. But if I remove the node inside the collision method instead of returning it, it works nicely.
-(CCSprite*)spriteCollisionWithRect:(CGRect)bounds
{
for (CCSprite *sprite in _spritesArray) {
if (CGRectIntersectsRect(sprite.boundingBox, bounds)) {
[sprite removeFromParentAndCleanup:YES];
}
}
return nil;
}
Why is this?
[_spritesArray removeObject:sprite];before the return, it works just fine! – Khalizar May 18 '12 at 11:25_spritesArrayin theupdatemethod, nex to theremoveFromParentAndCleanup, not insidespriteCollisionWithRect. Doing it there is giving a function that's supposed to be just checking for a state a side-effect -- an example of the action-at-a-distance anti-pattern (en.wikipedia.org/wiki/…). Also, just adding that to the logic leaves you only finding a maximum of one collision perupdatecycle. – chaos May 18 '12 at 19:27