可根据地形的不同,以及角色能力的不同来判断可移动区域。例如骑士在平地上可以移动更大的范围。
代码如下:
/**
* 搜索可走区域
* @param map 当前地图表
* @param row 行
* @param col 列
* @param locomotivity 该角色的默认移动力
* @param direction 方向
*/
public void scanmovablearea(byte map[][], int row, int col, int locomotivity, int direction){
if(locomotivity > map[row][col])
map[row][col] = (byte)locomotivity;
else
return;
/** 向上判断 **/
if(direction != 1){
int loco1 = locomotivity - mapexpendlocomotivity(row, col - 1);
if(loco1 >=0)
scanmovablearea(map, row, col - 1, loco1, 2);
}
/** 向下判断 **/
if(direction != 2){
int loco2 = locomotivity - mapexpendlocomotivity(row, col + 1);
if(loco2 >= 0)
scanmovablearea(map, row, col + 1, loco2, 1);
}
/** 向左判断 **/
if(direction != 4){
int loco3 = locomotivity - mapexpendlocomotivity(row - 1, col);
if(loco3 >= 0)
scanmovablearea(map, row - 1, col, loco3, 8);
}
/** 向右判断 **/
if(direction != 8){
int loco4 = locomotivity - mapexpendlocomotivity(row + 1, col);
if(loco4 >= 0)
scanmovablearea(map, row + 1, col, loco4, 4);
}
}
----------------------------------------------
/**
* 地形对移动力的消耗
* @param row 行
* @param col 列
* @return 移动力消耗值
*/
public int mapexpendlocomotivity(int row, int col){
//这里我就不一一实现了,有兴趣的朋友可以自己扩展这个方法。
//下面给个伪代码
//如果是草地
if(gamemap[row][col] == game_map_grass){
//如果是士兵
if(type == solider){
return 1;
}
}
//超出边界
if(row < 0 || col < 0 || row > gamewidth || col > gameheight)
{
return 1000;
}
//具体的情况各位朋友可以根据自己的游戏来设计。
}
找到可以移动的区域后,就可以确定要移动的具体位置。这时候又要涉及到找路算法了。对于与a*算法(以前有一位同事写过)。不过下次我会用递归算法来实现,速度更快,更简单。
差点忘记说明了以上得到的map数组怎么使用。这时一个记录了剩余移动力的数组。在显示可移动的区域的时候只要判断map里面的值是否为空,不为空就画出一个矩形,代表该区域可走。
/**
* 走路
* @param curx 当前位置 (x方向)
* @param cury 当前位置 (y方向)
* @param destx 目标位置(x方向)
* @param desty 目标位置 (y方向)
* @return 路径矢量
*/
public vector scanpath(int curx, int cury, int destx, int desty){
vector vector = null;
short dest[] = {
(short)destx, (short)desty
};
if(curx == destx && cury == desty){
vector = new vector();
vector.addelement((object)dest);
return vector;
}
byte byte0 = 0;
byte byte1 = 0;
byte byte2 = 0;
byte byte3 = 0;
if(desty > 0)
byte0 = _mapped_terrains[destx][desty - 1];
if(desty < _map_height - 1)
byte1 = _mapped_terrains[destx][desty + 1];
if(destx > 0)
byte2 = _mapped_terrains[destx - 1][desty];
if(destx < _map_width - 1)
byte3 = _mapped_terrains[destx + 1][desty];
int max = math.max(math.max((int)byte0, (int)byte1), math.max((int)byte2, (int)byte3));
if(max == byte0)
vector = scanpath(curx, cury, destx, desty - 1);
else
if(max == byte1)
vector = scanpath(curx, cury, destx, desty + 1);
else
if(max == byte2)
vector = scanpath(curx, cury, destx - 1, desty);
else
if(max == byte3)
vector = scanpath(curx, cury, destx + 1, desty);
vector.addelement((object)dest);
return vector;
}
还记得上个帖子上函数中传入的map参数吗,实际上通过那个函数就可以得到一个map,然后应用于现在的找路算法中,也就是上面代码段看到的_mapped_terrains
还有两个陌生的变量就是 _map_height和_map_width ,这个很简单了,就是slg地图中的长度和宽度。
呵呵,希望这些代码段对slg的朋友有些帮助。
闽公网安备 35060202000074号