【发布时间】:2012-08-27 18:42:51
【问题描述】:
在 cocos2d-x HelloWorld 项目中,我试图在 scene 中添加另一层,并在数据成员中保留对该层的引用。由于函数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() 是静态的,我不能在这个函数中添加层(因为我不能为层设置数据成员)。”,是错误的。
【问题讨论】: