计算Unity中的网格路径

时间:2018-01-22 05:51:40

标签: c# arrays unity3d

我有一个网格amd可以为玩家设置四个不同的移动方向

  • Vector2.up => (0,1)
  • Vector2.down => (0,-1)
  • Vector2.left => (-1,0)
  • Vector2.right => (1,0)

我有一个包含Cell个对象的二维数组。 Cell有一个bool isObstacle来检查玩家是否可以移动或必须停止。

private Cell[,] mapCells = new Cell[10, 10]; // the map is 10x10

填充数组时,我得到100个单元格。移动玩家时我想检查他是否能够进入特定方向。我通过一些if语句检查这个

  • 玩家不在外面移动
  • 下一个细胞不是障碍

我的代码

public Cell GetTargetCell(Vector2Int movementDirection) {
 Vector2Int targetCellIndex = new Vector2Int( /* currentPlayerPosX */ , /* currentPlayerPosY */ );

 while (targetCellIndex.x >= 0 &&
  targetCellIndex.y >= 0 &&
  targetCellIndex.x < mapCells.GetLength(0) &&
  targetCellIndex.y < mapCells.GetLength(1) &&
  !mapCells[targetCellIndex.x + movementDirection.x, targetCellIndex.y + movementDirection.y].IsObstacle) 
  {
  targetCellIndex += movementDirection;
  }

 return mapCells[targetCellIndex.x, targetCellIndex.y];
}

如你所见,我用第五个if语句检查下一个单元格。唯一的问题是,如果while循环达到了数组的最大索引,并且我添加了更高的索引,我将获得IndexOutOfRangeException

!mapCells[nextX, nextY].IsObstacle // this might be out of range

是否可以防止此错误?

1 个答案:

答案 0 :(得分:1)

只需检查targetCellIndex movementDirection是否在IsObstacle范围内。您目前正在检查&#34;旧的coord&#34;如果他们受到约束,然后检查&#34;新的coord&#34;是public Cell GetTargetCell(Vector2Int movementDirection) { Vector2Int targetCellIndex = new Vector2Int( /* currentPlayerPosX */ , /* currentPlayerPosY */ ); while (targetCellIndex.x + movementDirection.x >= 0 && targetCellIndex.y + movementDirection.y >= 0 && targetCellIndex.x + movementDirection.x < mapCells.GetLength(0) && targetCellIndex.y + movementDirection.y < mapCells.GetLength(1) && !mapCells[targetCellIndex.x, targetCellIndex.y + movementDirection.y].IsObstacle) { targetCellIndex += movementDirection; } else { //something wrong //do not move? to something else? your choice. } return mapCells[targetCellIndex.x, targetCellIndex.y]; } 。如果我的问题是正确的

{{1}}