cocos2dx游戏开发学习笔记(四)之Hello World

生命周期

Appdelegate控制程序的生命周期

applicationDidFinishLauching程序启动完成后执行


auto director = Director::getInstance();
auto glview = director->getOpenGLView();//初始化一个导演类

director->setDisplayStats(true);
director->setAnimationInterval(1.0f / 60);//设置帧率

auto scene = HelloWorld::createScene();//创建一个Hello World场景

director->runWithScene(scene);//通过导演类运行它


applicationDidEnterBackground程序进入后台的操作

Director::getInstance()->stopAnimation();//暂停程序

applicationWillEnterForeground程序进入前台的操作

Director::getInstance()->startAnimation();//开始程序

HelloWorldScene


class HelloWorld : public cocos2d::Scene//HelloWorld继承自Scene

里面实现了三个方法:

static cocos2d::Scene* createScene();创建场景

virtual bool init();初始化

先初始化父类

if ( !Scene::init() ){    return false;}

创建一个菜单项,包含两个图片,同时调用回调函数

auto closeItem = MenuItemImage::create(
                                           "CloseNormal.png",
                                           "CloseSelected.png",
                                           CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));

将菜单项添加到菜单中,并添加到场景中

auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);

创建hello world文字

auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);

添加背景图片


auto sprite = Sprite::create("HelloWorld.png");
this->addChild(sprite, 0);//第二个参数表示z轴的显示优先级,0表示最底层


void menuCloseCallback(cocos2d::Ref* pSender);回调函数

Director::getInstance()->end();//执行程序结束


CREATE_FUNC(HelloWorld);实现create并调用init的宏

下面是宏的具体代码

所做的事情就是创建create,调用初始化函数
#define CREATE_FUNC(__TYPE__) \
static __TYPE__* create() \
{ \
    __TYPE__ *pRet = new(std::nothrow) __TYPE__(); \
    if (pRet && pRet->init()) \
    { \
        pRet->autorelease(); \
        return pRet; \
    } \
    else \
    { \
        delete pRet; \
        pRet = nullptr; \
        return nullptr; \
    } \
}


在这里我尝试添加了一个标签的菜单项,并用setCallback的方式添加了回调函数

auto closeLabel = MenuItemLabel::create(Label::create("close", "fonts/Marker Felt.ttf", 24));
closeLabel->setPosition(Vec2(origin.x + visibleSize.width - closeLabel->getContentSize().width / 2,origin.y + 50));
closeLabel->setCallback(CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值