以下爲cocos2d-x版本2.2.5的項目HelloWorld的代碼流程走向:
一、main.cpp中的_tWinMain爲程序入口,其中代碼爲:
AppDelegate app;
CCEGLView* eglView = CCEGLView::sharedOpenGLView();
eglView->setViewName("helloworld by xing");
eglView->setFrameSize(480, 320);
return CCApplication::sharedApplication()->run();
1、AppDelegate 繼承於CCApplication,CCApplication這個類主要定義消息循環體Message Loop、獲取當前程序實例等功能;
2、AppDelegate 代表了cocos2d的應用程序cocos2d Application。定義了函數:applicationDidFinishLaunching(),該函數主要是負責實現控制器CCDirector和場景CCScene的初始化;applicationDidEnterBackground(),該函數在程序回到後臺運行時被調用;applicationWillEnterForeground(),該函數在程序回到桌面時被調用;
3、sharedOpenGLView()是CCEGLView的一個static方法。CCEGLView是一個窗體類,負責定義、創建窗體和初始化openGL的一些信息。在方法sharedOpenGLView()中實現這些。在CCEGLView中的Create中對定義窗口類、註冊和創建窗口對象,步驟跟MFC創建窗口的步驟一致;
4、eglView->setViewName("helloworld by xing") 和 eglView->setFrameSize(480, 320);是窗體的標題和框架大小屬性的設置;
5、方法CCApplication::sharedApplication()返回當前的程序實例指針,即爲第一行的app,相當於app->run();Appdelegate類中沒有實現run()方法,所以調用父類CCApplication中的run()方法。run()方法很重要,主要有以下幾個重要點:
- 調用applicationDidFinishLaunching(),該函數的作用:初始化遊戲引擎控制器CCDirector和窗體CCEGLView;設置FPS;創建helloworld的scene:CCScene *pScene = HelloWorld::scene(),其中helloWorld繼承於CCLayer,CClayer是CCNode的子類,負責實現觸摸事件控制的協議“ TouchEventsDelegate protocol”。在方法HelloWorld::scene()中先創建CCScene的對象scene,其中CCScene是CCNode的子類,只是用於抽象的概念,CCScene和CCNode大部分是一樣的,區別在於CCScene的錨點默認在於screen的中心,然後創建helloworld類型的layer(該layer是個autorelease的對象),並使用scene->addChild(layer)添加layer,最後返回scene。接着pDirector->runWithScene(pScene);運行返回的scene,在runWithScene中pushScene和開始啓動動畫startAnimation();
- 接下來獲取之前已定義的窗體指針或者創建窗體sharedOpenGLView()返回窗體指針,設置窗體在屏幕中的位置和顯示該窗體ShowWindow(這幾個步驟有點類似MFC的窗體實現流程);
- 接下來就是一個while(1){}循環,在該循環中:PeekMessage()獲取消息存放到信息體結構MSG(類似MFC),獲取時間並判斷是否到了獲取下一幀frame的時間點,如果是就會進行繪圖drawScene()和pop出對象;接下來就是TranslateMessage()和DispatchMessage()。
二、步驟走向:
main.cpp----->創建程序實例---》設置窗體屬性---》創建控制器和場景---》將場景置於控制器管理中的場景棧---》啓動動畫---》顯示窗體---》循環消息體(peek消息---》跳到下一場景---》trans消息---》dispatch消息---》peek消息)