自学cocos2d难免有错误的理解,作为参考吧
创建好Helloworld工程后,进入VS2012可以看到main主函数:
首先程序从主函数运行,代码如下:
#include "main.h"
#include "AppDelegate.h"
#include "cocos2d.h"
USING_NS_CC;
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();
}
创建完对象后的下一步才是最关键的。
(第二步)调用Application类里的getInstance()方法,这步我看了下源码基本上就是用一个指针指向app对象,然后通过该指针(第三步)调用run()方法。
进入run()方法后
int Application::run()
{
PVRFrameEnableControlWindow(false);
// Main message loop:
LARGE_INTEGER nFreq;
LARGE_INTEGER nLast;
LARGE_INTEGER nNow;
QueryPerformanceFrequency(&nFreq);
QueryPerformanceCounter(&nLast);
initGLContextAttrs();
// Initialize instance and cocos2d.
if (!applicationDidFinishLaunching())//(第四步)从这里进入AppDelegate类中初始化操作
{
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 - (nNow.QuadPart % _animationInterval.QuadPart);
director->mainLoop();
glview->pollEvents();
}
else
{
Sleep(1);
}
}
// 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;
}
在AppDelegate.cpp中查看applicationDidFinishLaunching()
bool AppDelegate::applicationDidFinishLaunching() {
// 初始化导演
auto director = Director::getInstance();//(第五步)进入系统默认的init()初始化
auto glview = director->getOpenGLView();//(第八步)创建OpenGL的对象
if(!glview) {
glview = GLViewImpl::create("My Game");
director->setOpenGLView(glview);
}
// (第九步)设置FPS的显示与否
director->setDisplayStats(true);
// (第十步)设置FPS值
director->setAnimationInterval(1.0 / 60);
// (第十一步)创建一个背景,这里面有用户自己写的init()方法初始化
auto scene = HelloWorld::createScene();
// 运行
director->runWithScene(scene);
return true;
}
第一句是创建导演对象以及初始化他,但是这个初始化init()不是Helloworld.cpp里面的init(),可以查看源码
Director* Director::getInstance()
{
if (!s_SharedDirector)
{
s_SharedDirector = new (std::nothrow) DisplayLinkDirector();
CCASSERT(s_SharedDirector, "FATAL: Not enough memory");
s_SharedDirector->init();//(第六步)在这里做初始化操作
}
return s_SharedDirector;
}
查看auto scene = HelloWorld::createScene();所用方法代码,可以看见
Scene* HelloWorld::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create(); //(第十二步)这里是调用Scene的init()方法
// 'layer' is an autorelease object
auto layer = HelloWorld::create(); //(第十三步)这里是调用了Helloworld的init()方法
//(第十四步)将图层加到背景上
scene->addChild(layer);
// return the scene
return scene;
}
调用create()方法后程序会调用各自的init()方法,
注意:第一次写博客语言表达肯能不太清晰,编写工具运用不太熟悉,谅解。