0
votes

For school I'm creating a tile based game. In this game I have a matrix that contains all the gameobjects of the board. If you select a tile with a unit on it I want to read the range of the unit en than highlight the tiles surrounding it in this range but how can i do that?

int x and int y are the positions of the tile in the grid. unit is the unit on the tile. this method is for getting the range of the unit.

private GameObject[,] grid;
public void unitSelected(int x, int y, GameObject unit)
{
    int rangeTiles = 0;
    Units u = (Units)Enum.Parse(typeof(Units), unit.tag);
    switch (u)
    {
        case Units.Lieutenent:
            Debug.Log("Luitenant");
            lieutenant lieut = unit.GetComponent<lieutenant>();
            rangeTiles = lieut.Movement;
            break;
        case Units.Bom:
            Debug.Log("Not yet implemented, Bom");
            break;

    }
    getTiles(x, y, rangeTiles);
}

private void getTiles(int x, int y, int moves)
{
    List<GameObject> moveTiles = new List<GameObject>();

}

How can i get all the tiles in range (moves) of the selectedtile (int x, int y) ?

1

1 Answers

1
votes

I haven't tested it, but your loop should look something like this.

private void getTiles(int x, int y, int moves)
{
    List<GameObject> moveTiles = new List<GameObject>();
    // sweep through horizontally
    for (int i = -moves; i <= moves; i++)
    {
        // at each step horizontally, sweep vertically as far as allowed
        int jRange = moves - Math.Abs(i);
        for (int j = -jRange; j <= jRange; j++)
        {
            // add (i + x, j + y) to moveTiles, maybe skip when (i, j) = (0, 0)?
        }
    }
}

As Sergey's answer said, remember to do range checking incase the tile isn't inside the grid.