How to get tile rotation from TileMapLayer in Godot 4
The 2D node TileMapLayer allows you to easily rotate tiles clockwise and counterclockwise and also allows you to flip them vertically and horizontally. Godot stores this information in the form of a hidden alternative tile. The ID of this tile contains the information about its transformations. You can extract it as follows:
for coord: Vector2i in tilemap.get_used_cells():
var alt := tm.get_cell_alternative_tile(coord)
var flip_h := alt&TileSetAtlasSource.TRANSFORM_FLIP_H > 0
var flip_v := alt&TileSetAtlasSource.TRANSFORM_FLIP_V > 0
var transpose := alt&TileSetAtlasSource.TRANSFORM_TRANSPOSE > 0
The actual rotation is nowhere in sight - that’s because it is encoded right into these parameters! This way the engine saves a bit of memory by packing the transforms into just three flags.
Here is how to reconstruct the rotation: 1
var rotation_y: float = 0.0
match [flip_v, flip_h, transpose]:
[false, false, false]:
pass # No rotation
[true, true, false]:
rotation_y = 180
[true, false, true]:
rotation_y = 90
[false, true, true]:
rotation_y = -90
_:
prints("Unknown rotation case:", flip_v, flip_h, transpose)
You could add more matches to also cover the cases when the tile is just flipped, but not actually rotated. But that’s trivial to see from the variables we already have!
Footnotes
-
I’m using the array pattern matching here, just because it’s more readable than a bunch of if statements. Match statement docs ↩