1. 简介
a星寻路作为启发式搜索,在游戏开发中经常使用,性能比dps要好,也比较简单好实现,通用原理网上很多这里就不多做详解了,还不熟悉的可以参考:简书链接;
2. 实现
伪码如下
把当前点加入openList
while(openList不为空){
取出f值最小的点作为当前点curGrid
if(curGrid == endGrid) 查找结束,生成路径
查找curGrid周围的点,如果不在openList则加入openList并重新排序, 这里要注意如果8方向查找要注意相邻的是不是障碍物
把curGrid从openList移除并加入closeList
if (openList为空) 则查找失败,没有路径
}
代码实现
let Grid = cc.Class({
ctor(){
this.x = 0;
this.y = 0;
this.f = 0;
this.g = 0;
this.h = 0;
this.parent = null;
this.type = 0; // -1障碍物, 0正常, 1目标点, 2起点
}
});
let AStar = cc.Class({
extends: cc.Component,
properties:{
map: cc.Graphics,
},
onLoad(){
this._gridW = 50; // 单元格子宽度
this._gridH = 50; // 单元格子高度
this.mapH = 13; // 纵向格子数量
this.mapW = 24; // 横向格子数量
this.is8dir = true; // 是否8方向寻路
this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
this.initMap();
},
onTouchMove(event){
let pos = event.getLocation();
let x = Math.floor(pos.x / (this._gridW + 2));
let y = Math.floor(pos.y / (this._gridH + 2));
if (this.gridsList[x][y].type == 0){
this.gridsLis