我在cocos2dx程序中声明了一些类,并为它们的成员变量设置了一些值,但是在每次程序循环(CCDirector的主循环)之后,它们的所有值都被删除了!我希望它类保存下一个场景,当场景应该被替换时,它应该被替换或推送(正如你可以在代码中看到的,2秒后,introPage类调用函数"IntoPageDone",场景应该被替换),我为下一个场景设置了一个名为 nextScene的变量,但在每次循环之后,它的值改变为NULL。请帮助我解决这个问题,还有有没有更好的方法处理场景和他们的变化??非常感谢!
StartingPage是一个继承自CCLayerColor的类。以下是CoCoGui.h文件:
#ifndef _COCOGUI_H_
#define _COCOGUI_H_
#include "StartingPage.h"
#include "IntroPage.h"
using namespace cocos2d;
class CoCoGui : public CCLayerColor{
public:
CoCoGui();
virtual ~CoCoGui(void);
virtual bool init();
static CCScene* scene();
CREATE_FUNC(CoCoGui);
private:
IntroPage * introPage;
StartingPage * startingPage;
void onEnterTransitionDidFinish();
};
#endif /* COCOGUI_H */
这是CoCoGui.cpp文件:
#include "CoCoGui.h"
#include <iostream>
using namespace std;
CCScene* CoCoGui::scene(){
CCScene *scene = CCScene::create();
CoCoGui *layer = CoCoGui::create();
scene->addChild(layer);
return scene;
}
CoCoGui::CoCoGui ( )
{
this->startingPage = new StartingPage ( );
this->introPage = new IntroPage ( );
}
CoCoGui::~CoCoGui(void)
{
delete introPage;
delete startingPage;
}
bool CoCoGui::init ( ){
if ( !CCLayerColor::initWithColor ( ccc4 (100,100,100,255) ) ){
return false;
}
return true;
}
void CoCoGui::onEnterTransitionDidFinish ( ){
this->introPage->setNextScene ( StartingPage::scene( ) );
CCScene * scene = NULL;
scene = IntroPage::scene();
CCTransitionFade * trans = CCTransitionFade::create( 0.4f, scene , ccBLACK);
CCDirector::sharedDirector()->pushScene(trans);
cout << "step" << endl;
}
这是introPage.h文件:
#ifndef INTROPAGE_H_
#define INTROPAGE_H_
#include "cocos2d.h"
#include "StartingPage.h"
using namespace cocos2d;
class IntroPage: public CCLayerColor {
public:
IntroPage( CCScene * nextScene );
IntroPage ( );
virtual ~IntroPage();
static CCScene* scene();
bool init();
void intoPageDone();
CREATE_FUNC(IntroPage);
CC_SYNTHESIZE_READONLY(CCLabelTTF*, _label, Label);
CCScene * getNextScene( );
void setNextScene ( CCScene * nScene );
private:
CCScene * nextScene;
};
#endif /* INTROPAGE_H_ */
还有 IntroPage.cpp:
#include "IntroPage.h"
IntroPage::IntroPage( CCScene * nextScene ) {
this->introPageDone = false;
this->setNextScene ( nextScene );
}
IntroPage::IntroPage( ){
}
IntroPage::~IntroPage() {
}
void IntroPage::setNextScene ( CCScene * nScene ){
this->nextScene = nScene;
}
CCScene* IntroPage::scene(){
CCScene *scene = CCScene::create();
IntroPage *layer = IntroPage::create();
scene->addChild(layer);
return scene;
}
bool IntroPage::init() {
if (CCLayerColor::initWithColor (ccc4(0, 0, 0, 255) )) {
this->runAction(
CCSequence::actions(CCDelayTime::actionWithDuration(2),
CCCallFunc::actionWithTarget(this,
callfunc_selector(IntroPage::intoPageDone)),
NULL));
return true;
}
return false;
}
void IntroPage::intoPageDone() {
this->introPageDone = true;
CCDirector::sharedDirector( )->popScene( );
CCDirector::sharedDirector( )->pushScene( this->nextScene );
}
我终于找到了答案!我们应该使用静态变量,这样它们就不会在主循环后被破坏