Detect tile under mouse cursor

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

Hi !
I’m fairly new to Godot, and I followed the TileMap tutorial + read a bit about the hexagonal tile map example, in order to trip to make a small hex-grid game.

I created a tileset with collision info and tiles set to “pickable”, with a custom signal being emitted on mouse_enter.

In the main scene, I added one callback per signal, to modify the content of a label depending on the tile under the cursor, but nothing happens.

I’m pretty sure I forgot to plug something, but I can’t find what… I’m uploaded my current project here.

If anyone can have a look, it would help a lot, thank you !

PS: here are a couple script shots if you can’t d/l the project but want to have a look:

By reading more about tilemap, I might have tried the wrong solution so I tested another one based on this _input function:

func _input(event):
	if event is InputEventMouseButton:
		var pos = event.position
		if event.pressed:
			print("Mouse Click at: ", pos)
			var tilemap = $TileMap
			var tile_pos = tilemap.world_to_map(pos)
			var cell = tilemap.get_cellv(tile_pos)
			# if cell == 3: # thetilesets tile id
			#	tilemap.set_cellv(tile_pos, 4)
			print("TM pos: ", pos)
			print("cell: ", cell)

			print("Mouse Unclick at: ", pos)

But as I expected, I don’t get the correct tile, because the base grid is square, and my tile (much like the hexmap tutorial) is not centered. Is it possible to fix this cell lookup “easily” or will I have to do it by hand ?

vinz | 2018-08-09 07:56

:bust_in_silhouette: Reply From: Zylann

Of course you may have read that “tiles are not nodes”, generally speaking, so nodes used in the tileset making process actually aren’t those ending up in the TileMap (that’s why the workflow even calls this “convert to tileset”).

It looks like a design problem with the TileMap node… I can see that even though your grid is hexagonal, the Godot TileMap is still using rectangular cells, with an offset. This is fine for drawing or editing cells maybe, but when picking hexagonal tiles actually matters then it’s no longer helpful.

So I guess you have to come up with a specific solution that works with hexagonal tiles with a bit of math, colliders shouldn’t be needed here since the pattern is so regular. You can also post an issue on Github to raise awareness about this problem, however I think you should try to fix this offset you have because even in map edition that looks confusing.

I think there’s already an issue on the subject here. Since the “official” example also has this offset, I think I’ll just comment on the existing issue. Thanks !

vinz | 2018-08-10 15:50