cocos2dx3.x版本的程序的初始化和运行流程和2.x版本类似。之前有过笔记,不过这里还是简单的笔记下:
CONTENTS
首先是main.cpp:
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // create the application instance AppDelegate app; return Application::getInstance()->run(); }
这里申请了一个变量app,然后调用了run方法。
我们先看下AppDelegate的实现代码:
class AppDelegate : private cocos2d::Application { //AppDelegate 继承自Application } ======= AppDelegate::AppDelegate() { //空的构造函数 } bool AppDelegate::applicationDidFinishLaunching() { // initialize director auto director = Director::getInstance(); auto glview = director->getOpenGLView(); if(!glview) { glview = GLView::create("TheWeaponRentalShop"); director->setOpenGLView(glview); } // turn on display FPS // director->setDisplayStats(true); // set FPS. the default value is 1.0/60 if you don't call this director->setAnimationInterval(1.0 / 60); // create a scene. it's an autorelease object auto scene = HelloWorld::createScene(); // run director->runWithScene(scene); return true; }
继续看下Application的实现:
class CC_DLL Application : public ApplicationProtocol { public: Application(); virtual ~Application(); int run(); static Application* getInstance(); 。。。。。 protected: 。。。。。 static Application * sm_pSharedApplication; }; ===== // sharedApplication pointer //静态成员变量初始化 Application * Application::sm_pSharedApplication = 0; Application::Application() : _instance(nullptr) , _accelTable(nullptr) { _instance = GetModuleHandle(nullptr); _animationInterval.QuadPart = 0; CC_ASSERT(! sm_pSharedApplication); sm_pSharedApplication = this; //调用构造函数时,会将this指针传递给sm_pSharedApplication。非常重要!! } Application::~Application() { CC_ASSERT(this == sm_pSharedApplication); sm_pSharedApplication = NULL; } int Application::run() { 。。。。。 // Initialize instance and cocos2d. //先初始化程序运行逻辑 if (!applicationDidFinishLaunching()) { return 0; } auto director = Director::getInstance(); auto glview = director->getOpenGLView(); // Retain glview to avoid glview being released in the while loop glview->retain(); //程序主循环 while(!glview->windowShouldClose()) { QueryPerformanceCounter(&nNow); if (nNow.QuadPart - nLast.QuadPart > _animationInterval.QuadPart)//帧数控制 { nLast.QuadPart = nNow.QuadPart; director->mainLoop();//程序主循环中调用director的mainLoop方法,实现游戏业务 glview->pollEvents(); //发送各种事件(滑动,单击等) } else { Sleep(0); } } //游戏结束后的清理工作 // Director should still do a cleanup if the window was closed manually. if (glview->isOpenGLReady()) { director->end(); director->mainLoop(); director = nullptr; } glview->release(); return true; } Application* Application::getInstance() { CC_ASSERT(sm_pSharedApplication); return sm_pSharedApplication;//返回静态成员变量 }
这里就很清晰了,在main函数的初始化中初始化了一个实例app,会调用到Application的构造函数中,这样Application中的sm_pSharedApplication就会被赋值为该app。之后调用run方法,就会县调用到Appdelegate::applicationDidFinishLaunching,然后进入游戏主循环。
发表评论