上节课写了关卡选择场景,那么接下来写关卡内容,先写最基本的地图的加载
我们新建一个场景类,如下所示:
class CityScene : public cocos2d::CCLayer { public: CityScene(); ~CityScene(); virtual bool init(); static cocos2d::CCScene *scene(); static cocos2d::CCScene *scene(int round); CREATE_FUNC(CityScene); static CityScene *create(int round); CC_SYNTHESIZE(int, m_nRound, Round); };
然后编写创建场景的一些函数,如下图:
CCScene *CityScene::scene() { CCScene* scene = CCScene::create(); CityScene* layer = CityScene::create(); scene->addChild(layer); return scene; } CCScene *CityScene::scene(int round) { CCScene* scene = CCScene::create(); CityScene* layer = CityScene::create(round); scene->addChild(layer); return scene; } CityScene *CityScene::create(int round) { CityScene* pRet = new CityScene(); if (pRet) { pRet->setRound(round); if (pRet->init()) { pRet->autorelease(); return pRet; } } return NULL; }
然后在 init 函数中加载一个tmx文件显示一下看看效果:
bool CityScene::init() { CCLayer::init(); CCTMXTiledMap* tmxFile = CCTMXTiledMap::create("Round1.tmx"); //将地图放到屏幕中间 CCSize winSize = CCDirector::sharedDirector()->getWinSize(); CCSize size = tmxFile->getContentSize(); tmxFile->setPosition(ccp((winSize.width - size.width)/2, (winSize.height - size.height)/2)); this->addChild(tmxFile); return true; }
void ChoiceScene::touchDownAction(CCObject* sender, unsigned int controlEvent) { if (controlEvent == evt_pressA) { m_nRound = 1 + (m_nRound - 1 + ROUNDS - 1) % ROUNDS; update(); } else if (controlEvent == evt_pressB) { m_nRound = 1 + (m_nRound + 1 + ROUNDS - 1) % ROUNDS; update(); } else if (controlEvent == evt_start) { //开始对应关卡的场景,稍后添加 CCScene* scene = CityScene::scene(); CCDirector::sharedDirector()->replaceScene(scene); } }
在上面可以看到加载了一个地图文件 “Round.tmx”,他是用Tiled地图编辑器生成的,
为了不打断程序编写流程,暂时不介绍他的使用方法,大家可以自己研究下。
Tiled下载地址:http://www.mapeditor.org/download.html
完整程序下载地址:
http://download.csdn.net/detail/yincheng01/6741255