How to use TileMapLayer in GDScript

Godot Version

Godot 4.3

Question

Hello, I’m trying to procedurally generate my 2d level via TileMapLayer but facing some challenges. I’ve already tried searching for solutions, but seems like there’s not too much information on it. (There are old posts that does not apply).

My current script doesn’t render anything onto the screen.

extends Node2D

@onready var parentNode = $Generation

var tileMapLayer: TileMapLayer

func _ready() -> void:
		
	var tileAtlas = TileSetAtlasSource.new()
	tileAtlas.texture = load("res://tiles/hexagonTerrain_sheet.png")
	tileAtlas.separation = Vector2i(2, 2)
	tileAtlas.texture_region_size = Vector2i(120, 140)
	
	var tileSet = TileSet.new()
	tileSet.tile_shape = TileSet.TILE_SHAPE_HEXAGON
	tileSet.tile_layout = TileSet.TILE_LAYOUT_DIAMOND_DOWN
	tileSet.tile_offset_axis = TileSet.TILE_OFFSET_AXIS_HORIZONTAL
	tileSet.tile_size = Vector2i(120, 140)
	tileSet.add_source(tileAtlas)	
	#tileAtlas.create_tile(Vector2i.ZERO, tileSet.tile_size)
	
	tileMapLayer = TileMapLayer.new()
	tileMapLayer.tile_set = tileSet
	tileMapLayer.set_cell(Vector2i(120, 140), tileSet.get_source_id(0), Vector2i(5,5))
		
	parentNode.add_child(tileMapLayer)

My scene:

Can you share the image resource you’re using? Just hosting on imgur works.

hexagonTerrain_sheet.png

It’s one of Kenny’s free assets:

I get a runtime error in the editor debugger because !room_for_tile is true in the TileAtlas implementation on line 20: tileAtlas.create_tile(Vector2i.ZERO, tileSet.tile_size)

“The tile is outside the texture or tiles are already present in the space the tile would cover.”

This error does not appear if I switch the texture_region_size assignment to be values less than Vector2i(31, 44) but fails for greater values. Obviously your texture isn’t smaller than 32, 45. I modified the tile_size in the TileSet to check if that was somehow related. I saw no change in behavior after doubling the tile_size.

I do also check the tile atlas’s tiles by calling get_tiles_count() to verify that the first case in the error is not the fault; it always returns 0 when I see that debug error. So the engine is complaining because it thinks it is being asked to create tiles outside of the image bounds. That doesn’t make sense to me given the provided image file which I am also working with in my test project.

Sorry I can’t help more right now, just trying to help by documenting what I can observe.

Thanks for trying it. For the error, I commented out the line that was causing it. But regardless, the tile is still not rendering.