0
votes

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!

1
Are you certain batch is initialized by the time you come to use it. Try an NSLog or a breakpoint to make sure as sending messages to nil objects just fails silently in objective-c - James Webster
I see is that you are adding the object to spriteBatch internally, instead of in the scope where you called initBallInWorld, which I'm betting is GameScene. A CCScene should not be a singleton. You're abusing the singleton paradigm. Fixing likely won't fix your problem, but it'll make you a better programmer. - user481081

1 Answers

0
votes

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.