cocos2dx(2)代码基本结构

来源:互联网 发布:自动驾驶分级 知乎 编辑:程序博客网 时间:2024/05/16 15:36

入口类,cocos2d::CCApplication类统一了各平台的差异


AppDelegate.h

#ifndef __APP_DELEGATE_H__#define __APP_DELEGATE_H__#include "cocos2d.h"class  AppDelegate : private cocos2d::CCApplication{public:    AppDelegate();    virtual ~AppDelegate();    virtual bool applicationDidFinishLaunching();//窗口启动完成,加载游戏,开启音乐等    virtual void applicationDidEnterBackground();//进入后台,游戏,音乐暂停等    virtual void applicationWillEnterForeground();//进入前台,游戏,音乐恢复};#endif  // __APP_DELEGATE_H__


AppDelegate.cpp

bool AppDelegate::applicationDidFinishLaunching(){        CCDirector *pDirector = CCDirector::sharedDirector();//初始化导演    pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());//绑定opengl窗口    pDirector->setDisplayStats(true);//是否显示fps    pDirector->setAnimationInterval(1.0 / 60);//fps默认为1.0 / 60    CCScene *pScene = HelloWorld::scene();//初始化场景    pDirector->runWithScene(pScene);//场景run    return true;}

HelloWorldScene.h

#ifndef __HELLOWORLD_SCENE_H__#define __HELLOWORLD_SCENE_H__#include "cocos2d.h"class HelloWorld : public cocos2d::CCLayer{public:       virtual bool init();      static cocos2d::CCScene* scene();    void menuCloseCallback(CCObject* pSender);//菜单关闭事件处理    void ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);//按键处理    CREATE_FUNC(HelloWorld);};#endif  // __HELLOWORLD_SCENE_H__


HelloWorldScene.cpp

#include "HelloWorldScene.h"using namespace cocos2d;CCScene* HelloWorld::scene(){    CCScene * scene = NULL;    do     {        scene = CCScene::create();        CC_BREAK_IF(! scene);        HelloWorld *layer = HelloWorld::create();        CC_BREAK_IF(! layer);        scene->addChild(layer);    } while (0);    return scene;}bool HelloWorld::init(){    bool bRet = false;    do     {        CC_BREAK_IF(! CCLayer::init());        CCMenuItemImage *pCloseItem = CCMenuItemImage::create(//定义推出菜单            "CloseNormal.png",            "CloseSelected.png",            this,            menu_selector(HelloWorld::menuCloseCallback));        CC_BREAK_IF(! pCloseItem);        pCloseItem->setPosition(ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20));        CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);        pMenu->setPosition(CCPointZero);        CC_BREAK_IF(! pMenu);        this->addChild(pMenu, 1);        CCLabelTTF* pLabel = CCLabelTTF::create("Hello World111", "Arial", 24);//定义label        CC_BREAK_IF(! pLabel);        CCSize size = CCDirector::sharedDirector()->getWinSize();        pLabel->setPosition(ccp(size.width / 2, size.height - 50));        this->addChild(pLabel, 1);        CCSprite* pSprite = CCSprite::create("HelloWorld.png");        CC_BREAK_IF(! pSprite);        pSprite->setPosition(ccp(size.width/2, size.height/2));        this->addChild(pSprite, 0);
this->setTouchEnabled(true);//设置监听        bRet = true;    } while (0);    return bRet;}void HelloWorld::menuCloseCallback(CCObject* pSender){    CCDirector::sharedDirector()->end();}