I have a script that extends TileMapLayer and I want it to be able to adapt to different TileShapes and TileLayouts. In particular, I want to be able to retrieve all the valid CellNeighbors of the TileSet.
There does not seem to be any built-in method to do that, so my solution was to test with get_neighbor_cell like this :
# There does not seem to be a way to access TileSet.CellNeighbor.values() ...
const _CELL_NEIGHBORS_VALUES: Array[TileSet.CellNeighbor] = [TileSet.CELL_NEIGHBOR_RIGHT_SIDE, ...]
# Valid CellNeighbors for this TileSet
var _valid_directions: Array[TileSet.CellNeighbor]
# Populate _valid_directions
for dir: TileSet.CellNeighbor in _CELL_NEIGHBORS_VALUES:
var cell: Vector2i = get_neighbor_cell(Vector2i.ZERO, dir)
if cell != Vector2i.ZERO:
_valid_directions.append(dir)
And it works ! But…
it throws Method/function failed. Returning: p_coords at each failed get_neighbor_cell call
it exploits undocumented behavior of get_neighbor_cell to check if the CellNeighbor is valid
Is there another (cleaner) way to do this ? Or at least to suppress the errors ?
If it matters, my use case is to retrieve a given number of tiles in a given direction from a given coordinate. For example, on a square tile set, retrieve the 3 tiles right of tile (0,0), which would be (1,0), (2,0) and (3,0).
I believe that retrieving the valid CellNeighbors is the only way to do this.
You can check how TileSet::get_neightbor_cell() is implemented and only check the needed cells depending on the TileSet configuration. Here’s the code:
Thanks, checking the implementation was a good idea.
Turns out my initial solution was wrong, because get_neighbor_cell supports more CellNeighbor values than checked by get_surrounding_cells (e.g. for a square shaped tile set, you can ask get_neighbor_cell for diagonals).
So, to achieve what I wanted to do, I checked the implementation of TileSet::get_surrounding_cells. I do not think there is currently a cleaner way to do this.
For anyone wandering here later, here is the gdscript code: