【发布时间】:2018-01-22 05:51:39
【问题描述】:
我有一个网格,可以为玩家设置四个不同的移动方向
- Vector2.up => (0,1)
- Vector2.down => (0,-1)
- Vector2.left => (-1,0)
- Vector2.right => (1,0)
我有一个包含Cell 对象的二维数组。 Cell 有一个布尔值 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
有没有可能避免这个错误?
【问题讨论】: