在这一部分,我们简单说明一下文件的结构.在新建一个文件的基础上,加入自制的瓦片地图.
文件结构
说明:
合理的文件结构有利于后续开发理解,之前犯了错,到最后结构混乱修改不便
一.创建项目
在文件夹下Shift+右键,选择:在此处打开命令行窗口,新建一个项目
二.获取资源.
我重新找了主角资源和地图资源,放在附件链接中.(之后可能会在此更新制作资源方法)
首先是地图,通过Tiled重新做了一个地图
地图有3层:
第一层是Wall,主角和敌人不能跑到墙上去,设定为7层
第二层是floor,主角主要在这里活动,设定为3层
第三层是BlackGround,拿来当填充背景的
每隔瓦片设定都是32X32大小的,地图总大小为80X10
第一步
修改APPDelegate.cpp,符合我们的屏幕大小
<span style="font-family:SimSun;"> auto director = Director::getInstance();
auto eglView =director->getOpenGLView();
if(!eglView) {
eglView = GLViewImpl::create("My Game");
eglView->setFrameSize(480,320);
//WIN32下窗体大小,宽高
director->setOpenGLView(eglView);
}
//director->setOpenGLView(eglView);
eglView->setDesignResolutionSize(480,320, ResolutionPolicy::SHOW_ALL);</span>
第二步
GameScene中添加我们需要的层
<span style="font-family:SimSun;"> auto scene = Scene::create();
auto gamelayer=GameLayer::create();
scene->addChild(gamelayer, 0);
auto operateLayer = OperateLayer::create();
scene->addChild(operateLayer, 1);
auto statelayer =StateLayer::create();
scene->addChild(statelayer);</span>
第三步
设置我们的层
GameLayer,游戏在这里处理
<span style="font-family:SimSun;">bool GameLayer::init()
{
bool ret = false;
do {
CC_BREAK_IF( !Layer::init());
_visiblesize = Director::getInstance()->getVisibleSize();
_origin = Director::getInstance()->getVisibleOrigin();
this->_viswidth = _visiblesize.width;
this->_visheight = _visiblesize.height;
auto map = MapLayer::create();
this->addChild(map,-100);
ret = true;
} while(0);
return ret;
}</span>
OperateLayer,我们的摇杆和按键等放在这里
<span style="font-family:SimSun;">bool OperateLayer::init()
{
bool ret = false;
do {
CC_BREAK_IF( !Layer::init() );
m_pjoystick = Joystick::create();
m_pjoystick->setJoystick(Vec2(50,50));
this->addChild(m_pjoystick);
ret = true;
} while(0);
return ret;
}</span>
StateLayer,主角的状态放在这里,我们先空着这一层
<span style="font-family:SimSun;">bool StateLayer::init()
{
bool ret = false;
do {
CC_BREAK_IF( !Layer::init() );
ret = true;
} while(0);
return ret;
}</span>
其中摇杆的写法,在这里我用向量描述,如果你愿意的话可以用其他的比如笛卡尔坐标什么的,还有这个写法可以分段速度,让角色实现走动和跑动,贴得核心代码:
<span style="font-family:SimSun;">void Joystick::updateJoystick(Touch* touch)
{
Vec2 hit = touch->getLocation();
float distance = start.getDistance(hit);
Vec2 direction = (hit - start).getNormalized();
if(distance < m_pJoystickr/2)
{
m_pJoystick->setPosition(start + (direction * distance));
}else if(distance >m_pJoystickr) {
m_pJoystick->setPosition(start + (direction * m_pJoystickr));
}else {
m_pJoystick->setPosition(start + (direction * m_pJoystickr/2));
}
}</span>
至于地图的载入方法:
<span style="font-family:SimSun;">bool MapLayer::init()
{
bool ret = false;
do {
CC_BREAK_IF( !Layer::init() );
this->initMapWithFile("mymap.tmx");
ret = true;
} while(0);
return ret;
}
void MapLayer::initMapWithFile(const char * path)
{
TMXTiledMap *TileMap = TMXTiledMap::create(path);
TileMap->setPosition(Vec2(0,0));
this->addChild(TileMap);
global->tileMap = TileMap;
}</span>
至此为止,运行之后应该可以看到一个可以拖动的摇杆+地图了