0

我对 Cocos2D 中的 addChild: 行为感到困惑,原因如下:

我有一个 CCNode 子类,它拥有一个 CCSprite 和一个 Box2DBody。我是这个子类的 -init 方法,我将精灵添加到主 GameScene 的 CCSpriteBatchNode 中,如下所示:

//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!
}

在主 GameScene 中我做: Ball *ball = [Ball ballInWorld...]

如果我这样做 [self addChild:ball],物理会按预期工作,但如果我不这样做,ballSprite 会卡在 (0, 0) .. 为什么会这样?批处理已经添加到 GameScene 中,并且 ballSprite 已经添加到批处理中,这个额外的 addChild 对我来说似乎很奇怪!

谢谢!

4

1 回答 1

0

感谢您的评论,但我想通了。

当我调用静态 [Ball ballInWorld:] 时,CCSprite 不会保留在 Ball 类中,而只保留在 CCSpriteBatchNode 中,所以我必须使用 addChild:ball 或使用 [[Ball alloc]init ...] 来保留精灵参考活着。

GameScene 是一个 CCLayer,我认为可以将其用作单例。

于 2011-09-07T22:38:58.230 回答