How can I check if a child is already on the layer before I add it?
[self addChild: this];
Thanks.
A fast, easy to use, free, and community supported 2D game engine
How can I check if a child is already on the layer before I add it?
[self addChild: this];
Thanks.
well, you should just write your code in such a way that such a scenario will not occur ;)
but if you absolutely have to:
for(CCNode * node in children)
will look through all the children added to current node, just check if it's already there
Basically it's a shooting mechanism and I'm checking if the bullet is still on screen or if its off screen it will have been removed and when the gun i shot it is re added to the layer
Easier to just create a variable I use "active" in the bullet class. Then if inactive setVisible false and check if active for collisions. If you need a bullet, loop through and grab the first not active one and reset. Adding and removing from an nsmutable array has cost, not a lot but this is faster and easier.
Can you give me some sample code because I'm struggling, thanks.
Hi javawizkid I was gone all day but here goes. This should solve both of your posts.
Subclass CCSprite to make a bullet class add a boolean
@interface Bullet:CCSprite
{
bool active;
}
@property bool active;
synthesize the property in implementation
then when you check if out of bounds pseudocode
for(int i = 0; i < 10; i++)
{
if(((CCSprite *)[bulletsBuilder objectAtIndex:i]).position.x > 490)
{
// not this
//[self removeChild:((CCSprite *)[bulletsBuilder objectAtIndex:i]) cleanup:YES];
bulletNumber--;
// do this
((CCSprite *)[bulletsBuilder objectAtIndex:i]).active=false;
((CCSprite *)[bulletsBuilder objectAtIndex:i]).visible = false;
}
}
Then when you need a new bullet loop through the array and look for the first that is !active and reset that one to the position you want set visible to true and your set.
This removes your problem with removing from an array in the loop in the other post to.
You must log in to post.