鉴于论坛js的氛围有点闷,特开源一个简单的A星四方向寻路。
说明:
- 本代码是我本人原创写的,并已经正常使用在我个人的项目里了
- MAP格式为二维数组,注意map里Y轴在前X轴在后,这样的目的是方便生成地图,当然你可以自己改
- MAP里障碍的数值为0
- 略高效
- 已经封装成类
- 可拓展成八反向
- 带注解
- 可随便使用,无需版权声明
var aStar = cc.Class.extend({
open : null, //待遍历的数组
close : null, //关闭数组
starPoint : null, //开始点
closePoint : null, //结束点
map : null, //地图数组
dirs : null, //上左下右
path : null, //路径数组
ctor:function(){},
findPath:function(start,end,m){
this.open = new Array();
this.close = new Array();
this.path = new Array();
this.starPoint = start;
this.closePoint = end;
this.map = m;
this.dirs = ,-1,0],,];
for (var i = 0; i < this.map.length; i++) {
this.close* = new Array();
for (var n = 0; n < this.map*.length; n++) {
this.close* = 0;
};
};
//加入起始节点
this.open.push(,
this.starPoint,
0,
(Math.abs(this.closePoint-this.starPoint)*10 + Math.abs(this.closePoint-this.starPoint)*10),
null
]);
return this.ergodicGrid(this.open);
},
//根据F值进行排序
fSort:function(a,b){
return a - b;
},
//循环遍历网格
ergodicGrid:function(g){
var around = this.getGridAround(g);
for (var i = 0; i < around.length; i++) {
//4.判断网格点是否为终点,为真则回溯路径点并结束遍历,为假则向下执行
if (around* == this.closePoint && around* == this.closePoint) {
console.log('end');
var ele = g;
this.path.unshift(,around*]);
do{
this.path.unshift(,ele]);
ele = ele;
}while(ele != null);
return this.path;
};
//5.计算四周网格点的GHF值压入open堆栈并设当前网格点为父坐标;
var G = g + 10;
var H = Math.abs(this.closePoint - around*) * 10 + Math.abs(this.closePoint - around*) * 10;
var F = G + H;
this.open.push(,around*,G,F,g]);
};
//6.将当前网格点压出open堆栈,并设置close数组坐标为1
var out = this.open.shift(); //open.shift删除并返回数组的第一个元素
this.close]] = 1;
//7.根据四周网格点F值重新排列open堆栈
this.open.sort(this.fSort);
//8.判断open堆栈是否为0,为真则返回null,为假则向下执行
if (this.open.length == 0) return null;
return this.ergodicGrid(this.open);
},
//获取网格点上左下右
getGridAround:function(g){
var a = new Array();
var xl = this.map.length;
var yl = this.map.length;
//1.获取当前网格点四周网格点坐标;
for (var i = 0; i < this.dirs.length; i++) {
var x = g + this.dirs*;
var y = g + this.dirs*;
if(x < 0 || x >= xl || y < 0 || y >= yl) continue;
//2.判断四周网格点是否为父坐标;为真则不做处理,为假则向下执行
if (g != null) {
if (x == g && y == g) continue;
};
//3.判断四周网格点是否为障碍或close数组里的坐标;为真则不处理,为假则向下执行
if (this.map == 0 || this.close == 1) continue;
a.push();
};
return a;
}
});
*
```
***********
*

