我在一个简单的 JavaScript 2D(画布)游戏中使用A* 寻路脚本。我将我的游戏分解为SSCCE。无论如何,我的游戏有 15 列和 10 行。
问题是什么?设置图表,节点只设置了 11 次横向和 10 次上下。X
轴应该是 up to when15
看起来它只设置到grid.length
which is 11
。好的,所以这是我的问题。Mygrid
是array
包含在SSCCE
.
这是我的SSCCE
。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type='text/javascript' src='graphstar.js'></script>
<script type="text/javascript">
var board;
</script>
<script type='text/javascript' src='astar.js'></script>
<script type="text/javascript">
$(document).ready(function()
{
// UP to DOWN - 11 Tiles (Y)
// LEFT to RIGHT - 16 Tiles (X)
graph = new Graph([
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1],
[1, 13, 1, 13, 13, 13, 13, 13, 1, 1, 1, 1, 1, 13, 13, 1],
[1, 13, 1, 1, 13, 1, 1, 13, 1, 13, 13, 1, 13, 13, 13, 1],
[1, 13, 13, 1, 1, 1, 13, 13, 1, 13, 13, 1, 1, 1, 13, 1],
[1, 13, 13, 1, 13, 1, 13, 13, 13, 13, 13, 1, 13, 13, 13, 1],
[1, 13, 13, 13, 13, 1, 13, 13, 13, 13, 13, 1, 13, 13, 13, 1],
[1, 13, 1, 13, 13, 13, 13, 13, 1, 1, 1, 1, 13, 13, 13, 1],
[1, 13, 1, 1, 1, 1, 13, 13, 13, 13, 1, 13, 13, 13, 13, 1],
[1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]);
//Let's do an example test.
start = graph.nodes[1][2]; // X: 1, Y: 2
end = graph.nodes[12][7]; // X: 12, Y: 7
result = astar.search(graph.nodes, start, end);
});
</script>
</head>
<body>
Loading... pathfinding. Look in Chrome Console/Firefox Firebug for more information.
</body>
</html>
如您所见,我grid
的11
上下行和16
列。然而,我graph
并没有那样解释它。
在这里查看全部内容:http graphstar.js
: //pastebin.com/KfS9ALFq(这里是astar.js
完整包: http: //pastebin.com/8WyWnTpQ)
这是它的布局graphstar.js
:
function Graph(grid) {
var nodes = [];
var row, rowLength, len = grid.length;
console.log("Length:" + len);
for (var x = 0; x < len; ++x) {
row = grid[x];
rowLength = row.length;
nodes[x] = new Array(rowLength);
for (var y = 0; y < rowLength; ++y) {
nodes[x][y] = new GraphNode(x, y, row[y]);
}
}
this.input = grid;
this.nodes = nodes;
}
如您所见,for
循环仅转到grid.length
( len
) ,11
因为它是11
行向下的。但那是X
轴。我的X
轴地图15
跨列,Y
轴向16
下行。
现在你说...你为什么不切换轴呢?我试过了。喜欢,X
并被Y
切换。但我得到的Uncaught TypeError: Cannot set property '0' of undefined
只是line 24
其中nodes[x][y] = new GraphNode(x, y, row[y]);
我怎样才能使图表相应地设置为X
最高轴是15
和Y
最高轴是10
?