下面的设计稍微繁琐一些,有必要把思路说清楚。
下一步的主要实现当我们点击Go按钮后,得到骰子随机数,就是行走的步数,根据步数获取行走的路径,然后角色根据路径移动位置。大体流程如图所示:
这其中getPath()获取路径的方法有必要说清楚,还是看流程图吧
思路大体是这样的,代码实现上可能存在一些差别,但是不影响我们的整体设计思想。
- GameBaseScene.h
- //新添加变量 表示地图块中每块的宽高
- const int tiledWidth = 32;
- const int tiledHeight = 32;
- class GameBaseScene: public Layer
- {
- public:
- int tiledColsCount; //关卡地图总的列数
- int tiledRowsCount;//关卡地图总的行数
- bool** canPassGrid;//根据地图总的行列数创建的二维数组
- virtual void initTiledGrid();//用来初始化canPassGrid数组
- void setWayPassToGrid();//根据地图图层way,设置canPassGrid相应的值为true
- void onExit();//退出时需要释放某些变量空间
- void addGoButton();//添加GO 按钮
- };
- 在init方法中添加新增函数的调用
- bool GameBaseScene::init()
- {
- …………………..
- addGoButton();
- initTiledGrid();
- setWayPassToGrid();
- …………….
- }
- void GameBaseScene::setWayPassToGrid()
- {
- TMXLayer* wayLayer = _map->layerNamed("way");//获取地图way图层
- Size _mapSize = wayLayer->getLayerSize(); //获取way图层大小
- //根据way图层,获取道路的坐标并转换成地图的行列值,设置canPassGrid相应的行列值为true,表示人物可以从这里通过
- for (int j = 0; j < _mapSize.width; j++) {
- for (int i = 0; i < _mapSize.height; i++) {
- Sprite* _sp = wayLayer->tileAt(Point(j,i));
- if (_sp)
- {
- float x = _sp->getPositionX();
- float y = _sp->getPositionY();
- int col = x/tiledWidth;
- int row = y/tiledHeight;
- canPassGrid[row][col] = true;
- log("canPassGrid row= %d,col =%d,canpass = %d",row,col,canPassGrid[row][col]);
- }
- }
- }
- log("setWayPassToGrid finished");
- }
- //这个就是简单 的添加Go按钮
- void GameBaseScene::addGoButton()
- {
- Sprite* goButton = Sprite::create(GO_BUTTON);
- goButton->setPosition(ccp(tableStartPosition_x+2*tableWidth,tableStartPosition_y-tableHeight*5));
- addChild(goButton);
- }
- //当退出是调用该函数,释放canPassGrid占用的空间
- void GameBaseScene::onExit()
- {
- CC_SAFE_DELETE(canPassGrid);
- Layer::onExit();
- }
下面看一下initTiledGrid()方法的实现,由于每个关卡地图大小不一样,所以这个方法的实现放到了子类中
SeaScene.cpp实现如下
- SeaScene实现父类GameBaseScene的initTiledGrid方法
- void GameBaseScene::initTiledGrid()
- {
- tiledColsCount = 20;//地图总的列数
- tiledRowsCount = 15;//地图总的行数
- //根据行列数创建二维数组canPassGrid
- canPassGrid = new bool*[tiledRowsCount];
- for(int i=0;i<tiledRowsCount;i++)
- canPassGrid[i]=new bool [tiledColsCount];
- //给canPassGrid设置默认值为false 表示不能通过
- for(int row = 0;row<tiledRowsCount;row++)
- {
- for(int col = 0;col<tiledColsCount;col++)
- {
- canPassGrid[row][col] = false;
- }
- }
- log("");
- }
Ok 至此我们已经可以调试一下代码,从log中可以看到已经打印出了canPassGrid数组中可以通过的行列值了
对比一下sea.tmx文件中的way图层 ,看看行列值是不是一致了
http://download.csdn.net/detail/lideguo1979/8276135
获取路径稍微复杂一些,我们分多章介绍
未完待续