cocos2d-x游戏开发系列教程-坦克大战游戏加载地图的编写

上节课写了关卡选择场景,那么接下来写关卡内容,先写最基本的地图的加载

我们新建一个场景类,如下所示:

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);
};

其中m_nRound存储关卡,可以初始化场景的时候带上关卡参数。

然后编写创建场景的一些函数,如下图:

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;
}

最后不要忘记在ChoiceScene.cpp中,点击开始的时候,替换场景为此场景:

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


posted on 2013-12-19 17:27  三少爷的剑123  阅读(315)  评论(0编辑  收藏  举报

导航