我在一个简单的JavaScript 2D(canvas)游戏中使用了一个A*路径搜索脚本。我将我的游戏分解成了一个SSCCE。不管怎样,我的游戏是15列横跨和10行向下。
问题是什么? 在设置图表时,节点只设置了11次横跨和10次向上和向下。X轴应该是到15,但实际上它只设置到grid.length,即11。好的,这就是我的问题。我的grid是在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
并不是这样解释的。在
graphstar.js
中可以查看整个代码:http://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
,位于第24
行,即nodes[x][y] = new GraphNode(x, y, row[y]);
我该如何设置图形,使得X
轴的最高点是15
,而Y
轴的最高点是10
?
未捕获的 TypeError: 无法读取未定义的属性“8”
,其中8
是我在“Y”轴上单击的数字。 - test