cocos2dx 3.x HelloWorld的代码认识

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; //返回场景

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值