开发者

Cocos2D addChild behaviour

开发者 https://www.devze.com 2023-04-03 08:14 出处:网络
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.

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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消