1. AppDelegate.cpp
bool AppDelegate::applicationDidFinishLaunching() {
// initialize director
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
if(!glview) {
glview = GLView::create("My Game");
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;
}
auto director = Director::getInstance(); // 初始化导演类
auto glview = director->getOpenGLView(); //通过导演类获取一个OpenGL窗口
director->setDisplayStats(true); //设置是否显示游戏的帧数等调试信息
director->setAnimationInterval(1.0 / 60); //设置游戏帧数,现在设置为1秒60帧
auto scene = HelloWorld::createScene(); //创建一个场景
director->runWithScene(scene); //只有执行这一步,才能让场景类显示出来
2.HelloWorldScene.h
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
class HelloWorld : public cocos2d::Layer
{
public:
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::Scene* createScene();
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// a selector callback
void menuCloseCallback(cocos2d::Ref* pSender);
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
};
#endif // __HELLOWORLD_SCENE_H__
场景类其实不是真正的场景,而新建一个场景类,是auto scene = HelloWorld::createScene();
CREATE_FUNC(HelloWorld);
#define CREATE_FUNC(__TYPE__) \
static __TYPE__* create() \
{ \
__TYPE__ *pRet = new __TYPE__(); \
if (pRet && pRet->init()) \
{ \
pRet->autorelease(); \
return pRet; \
} \
else \
{ \
delete pRet; \
pRet = NULL; \
return NULL; \
} \
}
参数__TYPE__ 其实是宏里面的宏,在编译的时候,会把__TYPE__全部替换为HelloWorld,其实 CREATE_FUNC(HelloWorld) 就是HelloWorld::create()函数,用来创建HelloWorld对象。
3. HelloWorldScene.cpp
Scene* HelloWorld::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
auto scene = Scene::create(); //创建一个场景类
auto layer = HelloWorld::create(); //创建HelloWorld对象,create函数正是用宏CREATE_FUNC(HelloWorld) 定义的。
scene->addChild(layer);// 将layer对象加到scene中
return scene; //返回场景