1
votes

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?

1

1 Answers

1
votes

Just check if your targetCellIndex with the movementDirection would be in the bounds. You currently check the "old coord" if they are in bound and then check the "new coord" to be IsObstacle. If i got your question correct

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];
}