在这个程序中,在main函数中,创建了一个Application:
int APIENTRY _tWinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPTSTR lpCmdLine,int nCmdShow){UNREFERENCED_PARAMETER(hPrevInstance);UNREFERENCED_PARAMETER(lpCmdLine);// create the application instanceAppDelegate app;return Application::getInstance()->run();}
其中AppDelegate继承自Application。这里明显使用了单例模式,AppDelegate构造时,Application内部的静态成员指针被赋值:
Application::Application(): _instance(nullptr), _accelTable(nullptr){_instance = GetModuleHandle(nullptr);_animationInterval.QuadPart = 0;CC_ASSERT(! sm_pSharedApplication);sm_pSharedApplication = this;}
其中sm_pSharedApplication即为静态成员。之后getInstance函数,便是返回了这个成员:
Application* Application::getInstance(){CC_ASSERT(sm_pSharedApplication);return sm_pSharedApplication;}
在main函数调用run之后,AppDelegate::applicationDidFinishLaunching会被调用,这个函数是一个虚函数,需要由用户指定实现。
在这个函数中,用户需要创建自己的场景。具体做法是,获取一个Director指针(Director也是单例模式),最后调用Director::runWithScene函数,把用户自定义的Scene加入:
bool AppDelegate::applicationDidFinishLaunching() {// initialize directorauto director = Director::getInstance();auto glview = director->getOpenGLView();if(!glview) {glview = GLViewImpl::create("Cpp Empty Test");director->setOpenGLView(glview);}director->setOpenGLView(glview);// turn on display FPSdirector->setDisplayStats(true);// set FPS. the default value is 1.0/60 if you don't call thisdirector->setAnimationInterval(1.0 / 60);// create a scene. it's an autorelease objectauto scene = HelloWorld::scene();// rundirector->runWithScene(scene);return true;}
上面代码中的HelloWorld是用户定义的类:
class HelloWorld : public cocos2d::Layer{public:// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphonevirtual bool init();// there's no 'id' in cpp, so we recommend returning the class instance pointerstatic cocos2d::Scene* scene();// a selector callbackvoid menuCloseCallback(Ref* sender);// implement the "static node()" method manuallyCREATE_FUNC(HelloWorld);};
实际上HelloWorld本身是一个Layer,调用scene函数的时候,会创建一个Scene的实例,调用scene的addChild函数把自身的一个实例加进去:
Scene* HelloWorld::scene(){// 'scene' is an autorelease objectauto scene = Scene::create();// 'layer' is an autorelease objectHelloWorld *layer = HelloWorld::create();// add layer as a child to scenescene->addChild(layer);// return the scenereturn scene;}
在create函数当中,会调用HelloWorld的init函数,这个函数是一个虚函数,在这个函数中,可以完成用户自身的初始化工作,例如加入菜单项,创建各种组成场景的元素。
总结一下,总的调用顺序是:
main调用Application::run
AppDelegate::applicationDidFinishLaunching被调用
创建Layer,Layer的init函数被调用
创建Scene,把Layer加进scene
获得Director指针(只有一个director),把Scene加进Director