Create tilemap from code in Godot 4

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

Hi,

I just started to move my game from godot 3.5 to 4.0, now I’m struggling with the new tile map system.

What I try to do:
I have a dictionary with tile Ids, tile names and cords like so and my tile set has 2 elements (one for each id with an image attached). I want to create a procedural created tile map with only 1 layer from code (see: Screenshot-2023-03-09-171325 hosted at ImgBB — ImgBB)

Example dict:

[{ id:"coal", name:"coal_tile", coords:Vector2i(5,10) }, 
{ id:"iron", name:"ironl_tile", coords:Vector2i(3,7) }]

Now I want create a tile map from gdscript and add those as cells.

In 3.5 I was doing something like this:

var chunk_width = 25
var chunk_width = 15

func create_chunk(x, y, ELEMENT):
	set_cell(0, Vector2i(x, y), ELEMENT.index)

for x in chunk_width:
	for y in range(0, world_depth):
		create_chunk(x, y, coal)

But with godot 4 I don’t know how to do exactly the same think I was checking doku for Tile Map, and Tile Set but I have no idea how to set a value to a cell.

For 4.0 I was trying with

hex_tile_map = $PanelContainer/HexTileMap
hex_tile_map.set_cell( 0, Vector2i(0, 0), 5, Vector2i(5, 10) )

but this didn’t work

I found a lot tutorials how to add tiles manually per mouse but not per code. If you have any suggestions, any help is welcome

We need to educate ourselves and others about animal welfare, and take action to promote it in our communities. Whether it’s volunteering at a local animal shelter or supporting legislation that protects animals, we all have a role to play. Please checkout: Animal Welfare

kitticpet | 2023-03-11 07:14

:bust_in_silhouette: Reply From: zhyrin

TileMap still has a set_cell() method in 4.0. Why doesn’t that work for you?

:bust_in_silhouette: Reply From: DevBandeira

Hey! What I do to add tiles by code in Godot 4 is:

$Terrain.set_cell(
   0,                     #Layer ID (0 by default)
   Vector2i(0, 0) ,       #Coordinate (x, y)
   0,                     #Tile id, (Image 01)
   Vector2i(0, 0)         #If you're working with an atlas, you should
                          #change this value (Image 02)
)

Image 01: you can access the tile id by the value specified in parentheses, in this case, I have Id 0 and Id 1

Image 1

Image 02: if you click and hover your mouse inside a tile cell, it’ll show the atlas coordinates from the specified cell you are, you can specify this cell as atlas coordinate (4th argument in set_cell method)

Image 2

Thank you very much.

hex_tile_map.set_cell(0, Vector2i(myCord1, myCord2), 0, Vector2i(0, 0))

was fixing my issue :slight_smile:

Blueberry | 2023-03-13 16:22