我有一个网格amd可以为玩家设置四个不同的移动方向
我有一个包含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
是否可以防止此错误?
答案 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}}