I can set four different movement directions for my player
- Vector2.up => (0,1)
- Vector2.down => (0,-1)
- Vector2.left => (-1,0)
- Vector2.right => (1,0)
and I have a two dimensional array that contains Cell
objects
public class Cell
{
public Cell(GameObject cellObject, bool isObstacle)
{
CellObject = cellObject;
IsObstacle = isObstacle;
}
public GameObject CellObject { get; set; }
public bool IsObstacle { get; set; }
}
My array is initialized by the size of the map.
private const int MAP_SIZE = 10;
private Cell[,] mapCells = new Cell[MAP_SIZE, MAP_SIZE];
I fill this array by using two loops, this will give me 100 cells.
for (int x = 0; x < MAP_SIZE; x++)
{
for (int y = 0; y < MAP_SIZE; y++)
{
Vector3 newCellPosition = new Vector3(x, 0, y);
GameObject newCellObject = Instantiate(cell, newCellPosition, cell.transform.rotation);
bool isObstacle = false; // TEST
Cell newCell = new Cell(newCellObject, isObstacle);
mapCells[x, y] = newCell;
}
}
When moving the player I want to return the Cell
he has to move to. The movementDirection parameter will set the row and the column to search for.
If there is an obstacle cell the player should just move to this obstacle and stop.
public Cell GetTargetCell(Vector2 movementDirection)
{
Cell targetCell = null;
// get the path
// get the closest obstacle
return targetCell;
}
Is there an elegant way to calculate the correct target cell by a 2D direction?