您的位置:首页 > 移动开发 > Cocos引擎

cocos2dx(2)代码基本结构

2013-06-04 21:37 183 查看
入口类,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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: