A*算法CocosCreator实现Demo

1.简介

A*星寻路算法是作为启发式搜索的算法,在游戏开发中经常使用,性能比dps要好的多,实现也比较简单好

简化寻路问题

搜索区域被划分为方形网格,简化搜索区域,是寻路的第一步。这一方法把搜索区域简化成了一个二维数组。数组的每一个元素是网格的一个方块,方块被标记为可通过和不可通过。路径描述为从A点到B点所经过的方块的集合。

Open和Closed列表

在A star寻路算法中,我们通过从A开始,检查相邻方格的方式,向外扩展直至找到目标。首先需要两个列表:
一个记录所有被考虑来寻找最短路径的网格集合(open list)
一个记录下不会被考虑的网格集合(closed list)
首先在closed列表中添加当前位置A,然后计算A格四周的所有格子可通行网格添加到open列表中,通过A星算法为每一个可行格子进行加权,被称为路径增量。

路径增量

我们将会给每个网格一个G+H的权重值:
G是从开始点A到当前方块的移动量。所以从开始点A到相邻小方块的移动量为1,该值会随着离开始点越来越远而增大。
H是从当前方块到目标点B的移动量估算值。该值经常被称为启发式的,因为我们不确定移动量是多少 – 仅仅是一个估算值。

A星算法的查询原理

使用CocosCreator实现A*算法的Demo

创建格子类

 

let GRID_TYPE=cc.Enum({
    //障碍物
    Type_0:0,
    //正常
    Type_1:1,
    //起点
    Type_2:2,
    //目的点
    Type_3:3,
})
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 = GRID_TYPE.Type_1;
    } 
});

实现A*组件类

初始化网格以及注册绘制路线事件

onLoad(){
    this._gridW = 50;   // 单元格子宽度
    this._gridH = 50;   // 单元格子高度
    this.mapH = 15;     // 纵向格子数量
    this.mapW = 25;     // 横向格子数量
    this.is8dir = true; // 是否8方向寻路
    this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
    this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
    this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
    this.initMap();
},
  initMap(){
    this.openList = [];
    this.closeList = [];
    this.path = [];
    // 初始化格子二维数组
    this.gridsList = new Array(this.mapW + 1);
    for (let col=0;col<this.gridsList.length; col++){
        this.gridsList[col] = new Array(this.mapH + 1);
    }
    this.map.clear();
    for (let col=0; col<= this.mapW; col++){
        for (let row=0; row<=this.mapH; row++){
            this.draw(col, row);
            this.addGrid(col, row, GRID_TYPE.Type_1);
        }
    }
    // 设置起点和终点
    let startX = 1;
    let startY = 2;
    let endX = 16;
    let endY = 3;
    this.gridsList[startX][startY].type = GRID_TYPE.Type_2;
    this.draw(startX, startY, cc.Color.MAGENTA);
    this.gridsList[endX][endY].type = GRID_TYPE.Type_3;
    this.draw(endX, endY, cc.Color.BLUE);
},
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 == GRID_TYPE.Type_1){
        this.gridsList[x][y].type = GRID_TYPE.Type_0;
        this.draw(x, y, cc.Color.CYAN);
    }
},
onTouchEnd(){
    // 开始寻路
    this.findPath(cc.v2(1, 2), cc.v2(16, 3));
},
draw(col, row, color){
    color = color != undefined ? color : cc.Color.GRAY;
    this.map.fillColor = color;
    let posX = 2 + col * (this._gridW + 2);
    let posY = 2 + row * (this._gridH + 2);
    this.map.fillRect(posX,posY,this._gridW,this._gridH);
}

添加网格单元

addGrid(x, y, type){
    let grid = new Grid();
    grid.x = x;
    grid.y = y;
    grid.type = type;
    this.gridsList[x][y] = grid;
}
sortFunc(x, y){
    return x.f - y.f;
},
generatePath(grid){
    this.path.push(grid);
    while (grid.parent){
        grid = grid.parent;
        this.path.push(grid);
    }
    cc.log("path.length: " + this.path.length);
    for (let i=0; i<this.path.length; i++){
        // 起点终点不覆盖,方便看效果
        if (i!=0 && i!= this.path.length-1){
            let grid = this.path[i];
            this.draw(grid.x, grid.y, cc.Color.GREEN);
        }
    }
},

**查询可行路径 **

findPath(startPos, endPos){
    let startGrid = this.gridsList[startPos.x][startPos.y];
    let endGrid = this.gridsList[endPos.x][endPos.y];
    this.openList.push(startGrid);
    let curGrid = this.openList[0];
    while (this.openList.length > 0 && curGrid.type != GRID_TYPE.Type_3){
        // 每次都取出f值最小的节点进行查找
        curGrid = this.openList[0];
        if (curGrid.type == GRID_TYPE.Type_3){
            cc.log("find path success.");
            this.generatePath(curGrid);
            return;
        }
        for(let i=-1; i<=1; i++){
            for(let j=-1; j<=1; j++){
                if (i !=0 || j != 0){
                    let col = curGrid.x + i;
                    let row = curGrid.y + j;
                    if (col >= 0 && row >= 0 && col <= this.mapW && row <= this.mapH
                        && this.gridsList[col][row].type != GRID_TYPE.Type_0
                        && this.closeList.indexOf(this.gridsList[col][row]) < 0){
                            if (this.is8dir){
                                // 8方向 斜向走动时要考虑相邻的是不是障碍物
                                if (this.gridsList[col-i][row].type == GRID_TYPE.Type_0 || this.gridsList[col][row-j].type == GRID_TYPE.Type_0){
                                    continue;
                                }
                            } else {
                                // 四方形行走
                                if (Math.abs(i) == Math.abs(j)){
                                    continue;
                                }
                            }
                            // 计算g值
                            let g = curGrid.g + parseInt(Math.sqrt(Math.pow(i*10,2) + Math.pow(j*10,2)));
                            if (this.gridsList[col][row].g == 0 || this.gridsList[col][row].g > g){
                                this.gridsList[col][row].g = g;
                                // 更新父节点
                                this.gridsList[col][row].parent = curGrid;
                            }
                            // 计算h值 manhattan估算法
                            this.gridsList[col][row].h = Math.abs(endPos.x - col) + Math.abs(endPos.y - row);
                            // 更新f值
                            this.gridsList[col][row].f = this.gridsList[col][row].g + this.gridsList[col][row].h;
                            // 如果不在开放列表里则添加到开放列表里
                            if (this.openList.indexOf(this.gridsList[col][row]) < 0){
                                this.openList.push(this.gridsList[col][row]);
                            }
                            // // 重新按照f值排序(升序排列)
                            // this.openList.sort(this._sortFunc);
                    }
                }
            }
        }
        // 遍历完四周节点后把当前节点加入关闭列表
        this.closeList.push(curGrid);
        // 从开放列表把当前节点移除
        this.openList.splice(this.openList.indexOf(curGrid), 1);
        if (this.openList.length <= 0){
            cc.log("find path failed.");
        }
        // 重新按照f值排序(升序排列)
        this.openList.sort(this.sortFunc);
    }
},

最终效果

留在个人博客以供学习:taoqy666.com

源码请到本站资源中寻找,谢谢!

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值