大家好,我正在写我自己的寻路脚本,先把它写在纸上,然后开始编码,让我告诉你们,这在实践中比理论上难得多。所以,我遇到了一个问题,我当然解决不了。
问题出现在以下图像中:
1)在这个镜头中,路径点被设置为(6,6),并且没有返回错误。
2)注意右上角的两个点,一个没有显示方向,另一个显示方向。错误是指向上方的节点。在这个镜头中,路径点被移动到(7,5),此时它开始抛出从最后一个索引开始的错误。我越往右下角移动,Y轴上的X=13点就会抛出更多的异常。
相关守则:
for (int x = 0; x < map.sizeX; x++)
{
for (int y = 0; y < map.sizeY; y++)
{
if (!(x == pVal.x && y == pVal.y) && map.grid[x, y].passable )
{
float dot = 1;
var heading = (grid[x, y].position - t.position).normalized;
heading.y = 0;
foreach (Vector3 direction in map.GetDirections())
{
var dot2 = Vector3.Dot(heading, direction.normalized);
if (dot > dot2 )
{
if (map.grid[x + (int)direction.x, y + (int)direction.y].passable)
{ // Error thrown when it reaches this if-statement \\
grid[x, y].direction = direction;
dot = dot2;
}
}
}
}
}
}
只有当我添加检查以查看指向方向的点是否可以通过时,才会引发此Index out of Bounds
错误。另外要注意的是,我使用的是direction.y
,其中的方向实际上存储在x和z中。由于某种原因,如果我使用z而不是y,它就会完全停止工作。
发布于 2016-11-26 18:42:22
创建一个简单的函数,在执行map.grid
之前检查您是否在if (map.grid[x + (int)direction.x, y + (int)direction.y].passable)
2D数组的范围内。
检查map.grid[x + (int)direction.x
是否小于map.sizeX-1
然后检查map.grid[ y + (int)direction.y]
是否小于map.sizeY-1
。
如果这两个条件都满足了,那么就使用if (map.grid[x + (int)direction.x, y + (int)direction.y].passable)
。
这里有一个简单的函数来简化这一点:
bool isWithinBound(Vector3 direction, int sizeX, int sizeY, int x, int y)
{
return ((x + (int)direction.x < sizeX - 1) && (y + (int)direction.y < sizeY - 1));
}
现在你可以做的就是:
for (int x = 0; x < map.sizeX; x++)
{
for (int y = 0; y < map.sizeY; y++)
{
if (!(x == pVal.x && y == pVal.y) && map.grid[x, y].passable)
{
float dot = 1;
var heading = (grid[x, y].position - t.position).normalized;
heading.y = 0;
foreach (Vector3 direction in map.GetDirections())
{
var dot2 = Vector3.Dot(heading, direction.normalized);
if (dot > dot2)
{
//Check if we are within bounds
if (isWithinBound(direction, map.sizeX, map.sizeY, x, y))
{
if (map.grid[x + (int)direction.x, y + (int)direction.y].passable)
{ // Error thrown when it reaches this if-statement \\
grid[x, y].direction = direction;
dot = dot2;
}
}
}
}
}
}
}
https://stackoverflow.com/questions/40819930
复制相似问题