0
votes

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.

Path

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?

1

1 Answers

1
votes

I think the most elegant way of doing it is by using two separate for loops and the ?: operator.

//returns cell
Cell GetTargetCell(Vector2 dir)
{
    if(dir.y == 0) //if we're going horizontal
    {
        //HorizontalMovement
        for(int i = 0; i < ((dir.x==1)?mapSize-PLAYER_X:PLAYER_X); i++)
        {
            if(mapCells[(int)dir.x*i,PLAYER_Y].IsObstacle()) //if we encounter an obstacle
                return mapCells[(int)dir.x*i,PLAYER_Y]; //return cell that's an obstacle
        }

        //if we didn't encounter an obstacle
        return mapCells[(dir.x == 1)?mapSize:0,PLAYER_Y]; //return the cell
    }
    else if(dir.x == 0)
    {
        //VerticalMovement
        //copy paste the previous for loop and edit the parameters, I'm too lazy :P
    }
    else
    {
        //NoMovement
        Debug.Log("Please enter a valid Direction");
        return mapCells[0,0];
    }


}

Replace the PLAYER_X and PLAYER_Y values, with the x, and y values of the cell the player is currently in. I didn't check if the code contains any errors, but I think it should work.