2012-07-04 50 views
5

我正在尝试实现A *在我的游戏中开始路径查找(使用JavaScript,HTML5 Canvas编写)。 A * Start的图书馆发现了这个 - http://46dogs.blogspot.com/2009/10/star-pathroute-finding-javascript-code.html,现在我正在使用这个库来寻找路径。 和这个库,我想写一个简单的测试,但坚持一个问题。 我现在完成时,在HTML5画布屏幕点击鼠标显示路径,直到我的mouse.x和mouse.y。下面是截图:*在HTML5 Canvas中开始路径查找

Screenshot.

(粉红色方形:球员,橙色方块:路径,直到我的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); 
} 

我的问题是我不明白如何将我的球员移动到路径目标。 我已经试过:

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

但有了这个代码,我的球员没有beung拉(当我运行代码,player.x和player.y都等于0,当我用鼠标点击我让路径播放器闪烁并消失)

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

而且我非常非常非常非常抱歉我的英语语言不好。 :)

+0

作为替代方案,您可以使用这个HTML5画布库:https://github.com/Zombitch/CellAStar(它是我使用的)。它提供了简单的例子。 – Ashbay

回答

5

My Working Fiddle

这是我目前使用的是基于关闭*我一个。这个概念应该是相同的。 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); 
}​ 
+2

很好的例子!有一个小错误,在你的鼠标处理代码中你应该使用'Math.floor',而不是'Math.round'!否则点击一个单元格的右半部分将它放在下一个单元格 –

+0

@SimonSarris好点啊! – Loktar

+0

非常感谢! :) – gyhgowvi