How do you use autotiling in code in godot 4?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ne_mene

I’m generating an island with noise and a falloff map, and I would ideally want the result to be autotiled, I couldn’t find anything on the docs. I’ve set up the autotiling terrain and it works in editor, now I just need to make it autotiled in code.

I have a single tile (id 1) called sand, one layer and a terrain that has a name “Autotile”

Help very apritiated!

Still nothing huh? I been trying to figure this out too.

RenderlessGames | 2023-07-06 01:50

Assuming that you already have done this preparation:
-get a grid with the noise values randomly generated
-Prepare the terrain in editor:
-In the tileset editor select the tileset,
-select Paint,
-in the Paint Properties select Terrains,
-select the Terrain Set properly. A new dropdown menu will appear where you will be able to choose the terrain you want to paint. Select it and simply paint it in the tiles.

What I do in code is the following:
-Create an array for each terrain type (to store the locations (Vector2i)). i.e.:
var sand_tiles = [ ]
-Loop through the noise grid and determine which type of terrain is each cell. Store it in the array. i.e.:
if noise_grid[i][j] > sand_low_thr and noise_grid[i][j] <= sand_upp_thr:
sand_tiles.append(Vector2i(i, j))

-Finally, call set_cells_terrain_connect on the tilemap to draw each type of tile. Suppose you have sand, sea, mountains, etc:
$Tilemap.set_cells_terrain_connect(layer, sand_tiles, terrain_set, sand_type, false)
$Tilemap.set_cells_terrain_connect(layer, sea_tiles, terrain_set, sea_type, false)
$Tilemap.set_cells_terrain_connect(layer, mountain_tiles, terrain_set, mountain_type, false)

In the above, sand_type, sea_type etc are the indexes of each type of terrain as they appear in Tileset properties in the Terrain Set you are using.

Hope this helps