Confusing Tilemap Coordinates

###Godot Version
4.2.1

Question

Hello,
I recently started tinkering with Godot and am trying to find out how to place instances of a building scene on a tilemap I created in the scene.

There are probably a lot of misconceptions I have about how tilemaps work and would really appreciate any and all help.
I use following code to place an instance:

func _input(event):
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
		
		var mouse_position = get_global_mouse_position()
		var grid_position = self.local_to_map(mouse_position)		
	
		if building_manager.building_type and building_manager.building_tier:
			var building_instance = building_manager.building_type.instantiate()
			building_instance.load_building_data(building_manager.building_tier)
			
			var offset = Vector2(-256, -768)
			building_instance.position = map_to_local(grid_position) + offset
			add_child(building_instance)

Now what has me completely baffled is the following:
I placed a tilemap in my scene and positioned it so that the origin of the tilemap is at (224, 808), all while believing the first cell will then be 0,0 at that position.
After testing it is instead at 2,6. I have no idea why that is or how to adjust it.

With my code I had to add an offset of 256,768 so that it gets even placed in the right cell. Cell size is 128. It being multiples of that suggests there is a connection.
Without the offset I would need to click the upper left corner to place the object at the start of the tilemap at (2,6).

i am aware my code is probably a complete hackjob, so input on that is very welcome.
(I guess the coding version of sorry for my bad english xD)

Thank you to anybody taking the time to help me out understanding this.

TileMap.local_to_map() expects local coordinates, but you’re using global mouse position. Try using get_local_mouse_position() instead.

1 Like

Thank you for the quick reply!
This is exactly what was wrong and now it correctly recognizes the cells and places the instances.

Thank you very much :slight_smile: