A*寻路算法 (cocos2d-js详细代码)
看了几天的A*算法,感觉要成为一个游戏开发者,有必要把这个著名的算法拿到手。
网上有此算法的代码片段,但主要还是些模板类的伪代码,所以想分享一段完整的A*算法代码供大家更好的理解!(这里使用的是js语言和cocos2d游戏引擎)
对于A*算法概念性的描述,请看这里,本篇主要以代码为主。
下面是我的学习成果,有晦涩和需改进的地方欢迎吐槽!
var A_STAR_DISTANCE = 7; //像素大小,越小越精确,同时越耗时
var A_STAR_G_EXPEND_MIN = 10; //上下左右G值消耗数
var A_STAR_G_EXPEND_MAX = 14; //斜角G值消耗数 var HelloWorldLayer = cc.Layer.extend({
sprite:null, //角色
aStarPathArray:[], //最终角色要行走的路径
aStarBarrierArray:[], //地图障碍物
testNumber:1,
ctor:function () {
//////////////////////////////
// 1. super init first
this._super();
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
// ask director the window size
var size = cc.director.getWinSize(); this.sprite = cc.Sprite.create(res.Plane_png); //角色初始化
this.sprite.attr({
x: 150,
y: 50,
rotation: 90
});
this.addChild(this.sprite, 0); var barrier1 = cc.rect(200,50,50,350); //绘制障碍物
var barrier2 = cc.rect(250,50,350,50);
var barrier3 = cc.rect(250,350,350,50);
this.aStarBarrierArray.push(barrier1);
this.aStarBarrierArray.push(barrier2);
this.aStarBarrierArray.push(barrier3); var drawBarrier = cc.DrawNode.create(); //在屏幕上显示障碍物
this.addChild(drawBarrier, 10);
var vertices = [cc.p(200,50),cc.p(600,50),cc.p(600,100),cc.p(250,100),cc.p(250,350),cc.p(600,350),cc.p(600,400),cc.p(200,400)];
drawBarrier.drawPoly(vertices,null,2,cc.color(255,0,0,255)); if ('mouse' in cc.sys.capabilities)
cc.eventManager.addListener({
event: cc.EventListener.MOUSE,
onMouseUp:function(event){
if(event.getButton() != undefined)
{
var t = new Date().getTime();
event.getCurrentTarget().getStartAndEndPoint(event); //A*算法开始
cc.log("算法耗时:"+(new Date().getTime() - t)+"ms"); //计算起点到终点的算法耗时
}
}
}, this); return true;
},
getStartAndEndPoint:function (event) { //得到起始点和终点坐标
var sp = {coordX:parseInt(this.sprite.x,10),coordY:parseInt(this.sprite.y,10)};
var ep = {coordX:parseInt(event.getLocation().x,10),coordY:parseInt(event.getLocation().y,10)};
var endPointIsObstacle = false; //判断终点是否在障碍物上,是的话就提示路径走不了
for (var theBarrierIndex=0; theBarrierIndex<this.aStarBarrierArray.length; theBarrierIndex++){
if(cc.rectContainsPoint(this.aStarBarrierArray[theBarrierIndex],cc.p(ep.coordX,ep.coordY)))
{
endPointIsObstacle = true;
cc.log("你要去的位置有障碍物,请换条路线");
break;
}
}
if(!endPointIsObstacle)
this.findingPath(sp,ep);
},
findingPath:function(startPoint,endPoint){ //A*算法
var openList = []; //初始化开启列表
var closeList = []; //初始化关闭列表
startPoint.ag = 0;
startPoint.ah = 0;
startPoint.af = startPoint.ag + startPoint.ah; //起点的G,H,F值为0
openList.push(startPoint); //起点加入开启列表
var findTheWay = false;
do{
var centerNode = this.findMinNode(openList); //寻找F值最低的节点
openList.remove(centerNode); //将此节点从开启列表中删除,为了下次遍历开启列表的时候不再出现此节点
closeList.push(centerNode); //并将此节点加入到关闭列表
for(var i=0;i<8;i++) //遍历此节点周围的节点,并给这些节点加入坐标属性和G值
{
var aroundNode = {};
switch (i){
case 0:
aroundNode.coordX = centerNode.coordX+A_STAR_DISTANCE; //坐标属性
aroundNode.coordY = centerNode.coordY+A_STAR_DISTANCE;
break;
case 1:
aroundNode.coordX = centerNode.coordX+A_STAR_DISTANCE;
aroundNode.coordY = centerNode.coordY;
break;
case 2:
aroundNode.coordX = centerNode.coordX+A_STAR_DISTANCE;
aroundNode.coordY = centerNode.coordY-A_STAR_DISTANCE;
break;
case 3:
aroundNode.coordX = centerNode.coordX;
aroundNode.coordY = centerNode.coordY-A_STAR_DISTANCE;
break;
case 4:
aroundNode.coordX = centerNode.coordX-A_STAR_DISTANCE;
aroundNode.coordY = centerNode.coordY-A_STAR_DISTANCE;
break;
case 5:
aroundNode.coordX = centerNode.coordX-A_STAR_DISTANCE;
aroundNode.coordY = centerNode.coordY;
break;
case 6:
aroundNode.coordX = centerNode.coordX-A_STAR_DISTANCE;
aroundNode.coordY = centerNode.coordY+A_STAR_DISTANCE;
break;
case 7:
aroundNode.coordX = centerNode.coordX;
aroundNode.coordY = centerNode.coordY+A_STAR_DISTANCE;
break;
}
for (var barrierIndex=0; barrierIndex<this.aStarBarrierArray.length; barrierIndex++){
aroundNode.isOb = cc.rectContainsPoint(this.aStarBarrierArray[barrierIndex],cc.p(aroundNode.coordX,aroundNode.coordY)); //判断当前节点是否在障碍物形成的方框里
if(aroundNode.isOb)
break;
}
if (aroundNode.isOb){ //如果是障碍物,跳过 }
else if(closeList.hasObject(aroundNode)){ //如果在关闭列表里,跳过 }
else if(!openList.hasObject(aroundNode)){ //如果不在开启列表里,加入到开启列表
aroundNode.parentPath = centerNode;
if (Math.abs(aroundNode.coordX-endPoint.coordX)<=A_STAR_DISTANCE/2 && Math.abs(aroundNode.coordY-endPoint.coordY)<=A_STAR_DISTANCE/2) //如果节点和终点的值相近,那么A*算法结束,得到路径
{
findTheWay = true;
var pathArry = [];
this.gettingAStarPath(aroundNode,pathArry); //寻找路径
pathArry.splice(0,0,{starX:endPoint.coordX,starY:endPoint.coordY}); //加终点到数组头部
pathArry.splice(pathArry.length-1,1); //删一项数组底部的起点数据,此时的数组是最终的路径数组 this.aStarPathArray = [];
this.aStarPathArray = pathArry;
this.aStarPathArray.theIndex = this.aStarPathArray.length; this.unschedule(this.thePathSelector);
this.schedule(this.thePathSelector,null,pathArry.length-1);
break; //找到最短路径并跳出循环
}
if (aroundNode.coordX!=centerNode.coordX && aroundNode.coordY!=centerNode.coordY) //确定中心节点和周围节点形成的角度,正交G值消耗10*像素,斜角G值消耗14*像素
aroundNode.ag = centerNode.ag + A_STAR_G_EXPEND_MAX*A_STAR_DISTANCE;
else
aroundNode.ag = centerNode.ag + A_STAR_G_EXPEND_MIN*A_STAR_DISTANCE;
aroundNode.af = this.getAF(aroundNode,endPoint);
openList.push(aroundNode);
}
else if(openList.hasObject(aroundNode)){ //如果在开启列表里
var newExpend = A_STAR_G_EXPEND_MIN*A_STAR_DISTANCE;
if (aroundNode.coordX!=centerNode.coordX && aroundNode.coordY!=centerNode.coordY) //确定中心节点和周围节点形成的角度,正交G值消耗10*像素,斜角G值消耗14*像素
newExpend = A_STAR_G_EXPEND_MAX*A_STAR_DISTANCE;
if (centerNode.ag + newExpend < aroundNode.ag){ //如果新的g值小于周围节点本身的g值,那么周围节点的父节点改为当前中心节点,并重新计算其F值
aroundNode.parentPath = centerNode;
aroundNode.ag = centerNode.ag + newExpend;
aroundNode.af = this.getAF(aroundNode,endPoint);
}
}
}
}while(!findTheWay) },
findMinNode:function(openListArray){
var minNode = openListArray[0];
for (var i=0;i<openListArray.length;i++)
{
if (minNode.af>openListArray[i].af) minNode=openListArray[i];
}
return minNode;
},
getAF:function(thisNode,endNode){
var aHExpend = (Math.abs(thisNode.coordX-endNode.coordX) + Math.abs(thisNode.coordY-endNode.coordY))*A_STAR_G_EXPEND_MIN;
return aHExpend+thisNode.ag;
},
gettingAStarPath:function(laseNode,array){
if(laseNode.parentPath != null)
{
array.push({starX:laseNode.parentPath.coordX,starY:laseNode.parentPath.coordY});
this.gettingAStarPath(laseNode.parentPath,array);
}
},
thePathSelector:function(){
this.roleRunThePath(this.aStarPathArray);
},
roleRunThePath:function(array){
this.sprite.x = array[--array.theIndex].starX;
this.sprite.y = array[array.theIndex].starY;
}
}); var HelloWorldScene = cc.Scene.extend({
onEnter:function () {
this._super();
var layer = new HelloWorldLayer();
this.addChild(layer);
}
}); //这里给Array数组添加3个实例方法
Array.prototype.aStarIndexOf = function(val) { //通过对象寻找index值
for (var i = 0; i < this.length; i++) {
if (this[i].coordX==val.coordX && this[i].coordY==val.coordY) return i;
}
return -1;
};
Array.prototype.remove = function(val) { //删除相应的对象
var index = this.aStarIndexOf(val);
if (index > -1) {
this.splice(index, 1);
}
}; Array.prototype.hasObject = function(val){ //判断是否是同一个对象
for (var i = 0; i < this.length; i++){
if (this[i].coordX==val.coordX && this[i].coordY==val.coordY)
return true;
}
return false;
};
如下图,飞机在寻找路径的时候会避开红色区域。

A*寻路算法 (cocos2d-js详细代码)的更多相关文章
- Python——EM(期望极大算法)教学(附详细代码与注解)
今天,我们详细的讲一下EM算法. 前提准备 Jupyter notebook 或 Pycharm 火狐浏览器或谷歌浏览器 win7或win10电脑一台 网盘提取csv数据 需求分析 实现高斯混合模型的 ...
- cocos2d JS 使用代码判断对象类型
changeAtlasScoreString : function (score,tfScore) { if(tfScore.getDescription() == "LabelAtlas& ...
- 如何在Cocos2D游戏中实现A*寻路算法(六)
大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请告诉我,如果觉得不错请多多支持点赞.谢谢! hopy ;) 免责申明:本博客提供的所有翻译文章原稿均来自互联网,仅供学习交流 ...
- js实现A*寻路算法
这两天在做百度前端技术学院的题目,其中有涉及到寻路相关的,于是就找来相关博客进行阅读. 看了Create Chen写的理解A*寻路算法具体过程之后,我很快就理解A*算法的原理.不得不说作者写的很好,通 ...
- 【转载】 A* 寻路算法 (个人认为最详细,最通俗易懂的一个版本)
原文地址: http://www.cppblog.com/christanxw/archive/2006/04/07/5126.html =============================== ...
- 如何在Cocos2D游戏中实现A*寻路算法(八)
大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请告诉我,如果觉得不错请多多支持点赞.谢谢! hopy ;) 免责申明:本博客提供的所有翻译文章原稿均来自互联网,仅供学习交流 ...
- 如何在Cocos2D游戏中实现A*寻路算法(一)
大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请告诉我,如果觉得不错请多多支持点赞.谢谢! hopy ;) 免责申明:本博客提供的所有翻译文章原稿均来自互联网,仅供学习交流 ...
- 6. EM算法-高斯混合模型GMM+Lasso详细代码实现
1. 前言 我们之前有介绍过4. EM算法-高斯混合模型GMM详细代码实现,在那片博文里面把GMM说涉及到的过程,可能会遇到的问题,基本讲了.今天我们升级下,主要一起解析下EM算法中GMM(搞事混合模 ...
- 4. EM算法-高斯混合模型GMM详细代码实现
1. EM算法-数学基础 2. EM算法-原理详解 3. EM算法-高斯混合模型GMM 4. EM算法-高斯混合模型GMM详细代码实现 5. EM算法-高斯混合模型GMM+Lasso 1. 前言 EM ...
- 数据挖掘领域十大经典算法之—C4.5算法(超详细附代码)
https://blog.csdn.net/fuqiuai/article/details/79456971 相关文章: 数据挖掘领域十大经典算法之—K-Means算法(超详细附代码) ...
随机推荐
- 一个方便且通用的导出数据到 Excel 的类库
一个方便且通用的导出数据到 Excel 的类库 起源: 之前在做一个项目时,客户提出了许多的导出数据的需求: 导出用户信息 导出业务实体信息 各种查询都要能导出 导出的数据要和界面上看到的一致 可以分 ...
- C++ 容器的综合应用的一个简单实例——文本查询程序
C++ 容器的综合应用的一个简单实例——文本查询程序 [0. 需求] 最近在粗略学习<C++ Primer 4th>的容器内容,关联容器的章节末尾有个很不错的实例.通过实现一个简单的文本查 ...
- Union 与 Union all 区别
原创,请园长不要删 Sql查询统计时,很多时候用到了union 和 union all,union与union all的区别就是联合查询的时候union会去重,union all不会去重.本人用uni ...
- redis beforesleep
本来想把redis main函数附带都读完再写笔记,但实在太大了,所以现在决定一部分一部分地记录. eventloop中在每次进入循环时都会调用beforeSleep回调(因为processevent ...
- 结构-行为-样式-Js函数节流
最近一个面试官问了我一个函数节流的问题,然后感觉自己工作中遇到过这个问题,但是不知道这种形式就是函数节流.下面我来说下这个Js的高级问题,思路:函数节流就是防止用户高频调用某个事件而做的Js层面的处理 ...
- webStorm支持.wxml文件高亮显示
微信小程序官方说明需要在微信开发者工具中开发运行,但这个工具着实不咋地. 我是使用webstrom编辑,然后在微信开发者工具中热加载查看效果,因为webstrom默认并不支持*.wxml,添加使用xm ...
- 删除style的样式JQuery
有些页面样式不规范,没有写在一个class里,例如:<div id="show" style="width:100px; padding-top:10px; f ...
- [Angular Directive] Implement Structural Directive Data Binding with Context in Angular
Just like in *ngFor, you're able to pass in data into your own structural directives. This is done b ...
- Python自动化开发-基础语法
1.编码 计算机只能处理数字,如果要处理文本,就必须先把文本转换为数字才能处理.解决思路:数字与符号建立一对一映射,用不同数字表示不同符号. ASCII(American Standard Code ...
- typeJavaScript笔记----字符串,参数,函数,表达式,循环
一.字符串新特性--双丿(撇)号声明字符串 .多行字符串 var myName = `fang my hao li jsk c sdf` //这样不会报错. .字符串模板 console.log(`q ...