在 cocos2d-x HelloWorld 项目中,我试图在场景中添加另一个图层,并在数据成员中保留对该图层的引用。由于该函数HelloWorld::scene()
是静态的,因此我无法在此函数中添加图层(因为我无法为图层设置数据成员)。
因此,我尝试按如下方式在函数中获取场景init()
,但这会导致scene = 0x00000000
.
我究竟做错了什么?
bool HelloWorld::init()
{
bool bRet = false;
do
{
CC_BREAK_IF(! CCLayer::init());
CCScene* scene = NULL;
scene = CCDirector::sharedDirector()->getRunningScene();
// add another layer
HelloWorldHud* layerHud = HelloWorldHud::create();
CC_BREAK_IF(! layerHud);
// set data member
this->layerHud = layerHud;
// next line crashes (because scene is 0x00000000)
scene->addChild(layerHud);
bRet = true;
} while (0);
return bRet;
}
PS:我想将 hud 图层添加到场景而不是当前图层的原因是因为我正在移动当前图层并且不希望 hud 图层随之移动。
编辑:由于接受的答案允许多个选项,这就是我解决问题的方法:
1.) 从 init() 函数中移除了 HUD 层:
bool HelloWorld::init()
{
bool bRet = false;
do
{
CC_BREAK_IF(! CCLayer::init());
bRet = true;
} while (0);
return bRet;
}
2.) 而是将 HUD 层添加到场景功能中(这也是 cocos2d-iphone 中的方式):
CCScene* HelloWorld::scene()
{
CCScene * scene = NULL;
do
{
// scene
scene = CCScene::create();
CC_BREAK_IF(! scene);
// HelloWorld layer
HelloWorld *layer = HelloWorld::create();
CC_BREAK_IF(! layer);
scene->addChild(layer);
// HUD layer
HelloWorldHud* layerHud = HelloWorldHud::create();
CC_BREAK_IF(! layerHud);
scene->addChild(layerHud);
// set data member
layer->layerHud = layerHud;
} while (0);
// return the scene
return scene;
}
本质上问题是我的假设,“因为函数HelloWorld::scene()
是静态的,我不能在这个函数中添加层(因为我不能为层设置数据成员)。”,是错误的。