参考:http://www.cnblogs.com/yung/archive/2009/07/03/1516102.html
什么是寻路算法?
寻路算法就是游戏中,绕开障碍物,到达目标点的一种算法
寻路算法有很多,但是怎么绕开障碍物并且以最适合的线路走,一直是大家研究的焦点
A*寻路算法是游戏中比较经典比较常用的算法。
初次研究,我也参考了不少文档,现在整理和核心代码与大家分享
下面是演示
黄色的代表路,黑色代表障碍物,绿色代表小人,点击鼠标到任意位置,小人就会自动寻路到此位置
下面是核心代码(参考一位高人的代码写的)
private function seekRoad():Array
{
var path:Array = new Array();
//判断目标点是不是障碍物
if(mCoordinate[mTargetIX][mTargetIY] == 1)
{
return path;
}
//寻路初始化
mUnlockList = new Array();
mLockList = new Object();
//初始化标记
var ix:int = mMan.ix;
var iy:int = mMan.iy;
//创建开始标记
var sign:Sign = new Sign(ix,iy,0,0,null);
mLockList[ix+"_"+ iy] = sign;
while(true)
{
//生成八方的标记开启
AddUnlockList(CreateSign(ix+1, iy-1,true,sign));
AddUnlockList(CreateSign(ix+1, iy,false,sign));
AddUnlockList(CreateSign(ix+1, iy+1,true,sign));
AddUnlockList(CreateSign(ix-1, iy-1,true,sign));
AddUnlockList(CreateSign(ix-1, iy,false,sign));
AddUnlockList(CreateSign(ix-1, iy+1,true,sign));
AddUnlockList(CreateSign(ix, iy-1,false,sign));
AddUnlockList(CreateSign(ix, iy+1,false,sign));
//判断开启列表是否已经为空
if(mUnlockList.length == 0){
break;
}
//从开启列表中取出h值最低的标记
mUnlockList.sortOn("f", Array.NUMERIC);
sign = mUnlockList.shift();
mLockList[sign.ix+"_"+ sign.iy] = sign;
ix = sign.ix;
iy = sign.iy;
//判断是否找出路径
if(ix == mTargetIX && iy == mTargetIY)
{
while(sign != null)
{
path.push(sign.getSign());
sign = sign.p;
}
break;
}
}
sign = null;
return path.reverse();
}
{
var path:Array = new Array();
//判断目标点是不是障碍物
if(mCoordinate[mTargetIX][mTargetIY] == 1)
{
return path;
}
//寻路初始化
mUnlockList = new Array();
mLockList = new Object();
//初始化标记
var ix:int = mMan.ix;
var iy:int = mMan.iy;
//创建开始标记
var sign:Sign = new Sign(ix,iy,0,0,null);
mLockList[ix+"_"+ iy] = sign;
while(true)
{
//生成八方的标记开启
AddUnlockList(CreateSign(ix+1, iy-1,true,sign));
AddUnlockList(CreateSign(ix+1, iy,false,sign));
AddUnlockList(CreateSign(ix+1, iy+1,true,sign));
AddUnlockList(CreateSign(ix-1, iy-1,true,sign));
AddUnlockList(CreateSign(ix-1, iy,false,sign));
AddUnlockList(CreateSign(ix-1, iy+1,true,sign));
AddUnlockList(CreateSign(ix, iy-1,false,sign));
AddUnlockList(CreateSign(ix, iy+1,false,sign));
//判断开启列表是否已经为空
if(mUnlockList.length == 0){
break;
}
//从开启列表中取出h值最低的标记
mUnlockList.sortOn("f", Array.NUMERIC);
sign = mUnlockList.shift();
mLockList[sign.ix+"_"+ sign.iy] = sign;
ix = sign.ix;
iy = sign.iy;
//判断是否找出路径
if(ix == mTargetIX && iy == mTargetIY)
{
while(sign != null)
{
path.push(sign.getSign());
sign = sign.p;
}
break;
}
}
sign = null;
return path.reverse();
}