我使用easystarjs https://github.com/prettymuchbryce/easystarjs并从页面上的示例开始。
var grid = [[0,0,1,0,0],
[0,0,1,0,0],
[0,0,1,0,0],
[0,0,1,0,0],
[0,0,1,0,0]];
//startX, startY ,endX, endY, callback
easystar.findPath(0, 3, 4, 3, function( path ) {
path = path || [];
for(var i = 0, ilen = path.length; i < ilen; i++) {
//console.log(path[i].x, path[i].y);
marker.drawRect(path[i].x*32, path[i].y*32, 32, 32);
}
});
如果我运行代码,则无法绘制出来,因为它不完整(路上有一堵墙,其中有第一名)。是否可以修改代码,以便我希望代码绘制尽可能远的路径(到墙上),而不只是说找不到路径(或没有绘图)。
如果我将数字一更改为数字零(并创建一个段落),该代码就会起作用。
最佳答案
该函数将返回不同的结果,具体取决于您转向 0
的 1
,因此“尽可能”是相对于此而言的。
只要这样,如果路径为空,您可以这样填充它:
currentX = startX;
currentY = startY;
path = [];
while(grid[currentY][currentX] != 1){
path.push({x: currentX, y: currentY});
dX = endX - currentX;
dY = endY - currentY;
distanceX = Math.abs(dX);
distanceY = Math.abs(dY);
directionX = dX / distanceX;
directionY = dY / distanceY;
// Make a step in the direction where the distance is bigger
if(distanceX > distanceY){
currentX += directionX;
}else{
currentY += directionY;
}
}
这将是一条通往目的地的直线,被墙壁打断。
关于javascript - 如何用easystarjs尽可能的走路,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23287745/