I have a grid amd can set four different movement directions for the player
- Vector2.up => (0,1)
- Vector2.down => (0,-1)
- Vector2.left => (-1,0)
- Vector2.right => (1,0)
I have a two dimensional array that contains Cell
objects. Cell
has a bool isObstacle
to check if the player can move along or has to stop.
private Cell[,] mapCells = new Cell[10, 10]; // the map is 10x10
When filling the array I get 100 cells. When moving the player I want to check if he is able to move into a specific direction. I check this by some if statements
- the player is not moving outside
- the next cell is not an obstacle
My code
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];
}
As you can see I check the next cell with my fifth if statement. The only problem is that if the while loop reached the maximum index for the array and I add a higher index I will get an IndexOutOfRangeException
.
!mapCells[nextX, nextY].IsObstacle // this might be out of range
Is it possible to prevent this error?