Question

I'm confused with the addChild: behavior in Cocos2D, because of the following:

I have a CCNode subclass that owns a CCSprite and a Box2DBody. Im the -init method of this subclass, i add the sprite to a CCSpriteBatchNode of the main GameScene, like this:

//Ball class, CCNode subclass with a CCSprite and a b2Body
-(id)initBallInWorld:(b2World *)word spriteFile:(NSString *)file
{
   //self = [super init] blablabla
   CCSpriteBatchNode *batch = [GameScene getSpriteBatch];  //singleton

   //create Box2dBody inside the world
   //create a CCSprite
   [batch addChild:sprite];   //Here is the confusion!
}

In the main GameScene i do: Ball *ball = [Ball ballInWorld...]

If i do [self addChild:ball], the physics works as expected, but if i don't, the ballSprite gets stuck at (0, 0)..why is that? The batch is already added to the GameScene, and the ballSprite is already added to the batch, this extra addChild seems weird to me!

Thanks!

Was it helpful?

Solution

Thanks for the comments, but i figure it out.

When i call the static [Ball ballInWorld:] the CCSprite is not retained in the Ball class, but only inside the CCSpriteBatchNode, so i have to use addChild:ball or use [[Ball alloc]init ...]to keep the sprite reference alive.

GameScene is a CCLayer, i think thats ok to use it as a singleton.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top