A*HTML5 Canvas中的开始路径查找

gyh*_*wvi 5 javascript html5 canvas a-star path-finding

我正在尝试在我的游戏中使用实现A*开始路径查找(使用JavaScript,HTML5 Canvas编写).A*Start的库找到了这个 - http://46dogs.blogspot.com/2009/10/star-pathroute-finding-javascript-code.html现在我正在使用这个库进行路径查找.有了这个库,我正在尝试编写一个简单的测试,但是遇到了一个问题.我现在已经完成了在HTML5画布屏幕上单击鼠标显示路径,直到我的mouse.x和mouse.y.这是一个截图:

截图.

(粉色方块:播放器,橙色方块:直到我的mouse.x/mouse.y的路径)编码如何绘制橙色方块,直到我的mouse.x/mouse.y为:

for(var i = 0; i < path.length; i++) {
    context.fillStyle = 'orange';
    context.fillRect(path[i].x * 16, path[i].y * 16, 16, 16);
}
Run Code Online (Sandbox Code Playgroud)

我的问题是我不明白如何移动我的球员直到路径目标.我试过了:

for(var i = 0; i < path.length; i++) {
    player.x += path[i].x;
    player.y += path[i].y;
}
Run Code Online (Sandbox Code Playgroud)

但是使用这个代码我的播放器并没有被绘制.(当我运行代码时,player.x和player.y等于0,当我用鼠标点击时,我得到路径播放器闪烁并消失)

也许有人知道如何解决这个问题?

对于我糟糕的英语,我非常抱歉.:)

Lok*_*tar 5

我的工作小提琴

这是我目前使用的基于我的**.这个概念应该是相同的.a*函数应该将路径作为数组返回,然后您只需要遍历每个播放器更新的路径并移动它们.

// data holds the array of points returned by the a* alg, step is the current point you're on.
function movePlayer(data, step){
    step++;
    if(step >= data.length){
        return false;   
    }

    // set the player to the next point in the data array
    playerObj.x = data[step].x;
    playerObj.y = data[step].y; 

    // fill the rect that the player is on
    ctx.fillStyle = "rgb(200,0,0)";
    ctx.fillRect(playerObj.x*tileSize, playerObj.y*tileSize, tileSize, tileSize);

    // do it again
    setTimeout(function(){movePlayer(data,step)},10);
}?
Run Code Online (Sandbox Code Playgroud)

  • 好例子!有一个小错误,在你的鼠标处理代码中你应该使用`Math.floor`,而不是`Math.round`!否则,单击单元格的右半部分会将其放入下一个单元格中 (2认同)