cocos2dx 中 scene(), create(), init() 调用关系

最近在学cocos2d,刚上手时对示例程序的函数调用关系不是很清楚。昨晚刚刚搞清楚,记录下。

1. 首先来看main函数:

    AppDelegate app; // 创建一个AppDelegate对象
    ...
    return CCApplication::sharedApplication()->run(); // 运行 app 对象

2. 再看 AppDelegate 类:

virtual bool applicationDidFinishLaunching(); // CCApplication::sharedApplication()->run(); 之后首先执行此函数
// Implement CCDirector and CCScene init code here.
bool AppDelegate::applicationDidFinishLaunching() {
    ...
    // create a scene. it's an autorelease object
    CCScene *pScene = HelloWorld::scene();
    pDirector->runWithScene(pScene);
    return true;
}

调用了层类(Layer)HelloWorld 的scene() 方法,并且通过 CCDirector 的一个实例来执行。

3. 最后看 HelloWorld 的 scene() 方法

CCScene* HelloWorld::scene()
{
    // 'scene' is an autorelease object
    CCScene *scene = CCScene::create();
    
    // 'layer' is an autorelease object
    HelloWorld *layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}
这时候会有疑问,那 HelloWorld::init() 方法在哪儿使用了?而且 HelloWorld 哪儿有 create() 方法?

这个时候,定位create() 方法,指向 CREATE_FUNC(HelloWorld);

/**
 * define a create function for a specific type, such as CCLayer
 * @__TYPE__ class type to add create(), such as CCLayer
 */
#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; \
    } \
}
根据宏定义可以知道,create() 即为CREATE_FUNC();将__TYPE__换成 HelloWorld 之后,则在 if 判断中调用了 init() 函数


4. 总结

调用顺序为 main() -> AppDelegate ->HelloWorld::scene() -> CREATE_FUNC() -> init()

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值