Get cell name from Tilemap

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

Good afternoon.
I am using raycast 2d for collision checking.
Can I check collision and get cell name from tilemap?
Grateful for any help!

:bust_in_silhouette: Reply From: fatcat__25

(Before I start, I am running 3.4.2, if that makes a difference.)

The method I use to get a tile name is as follows.

1: Have a reference saved of your tilemap.

var tilemap = get_node_or_null("path to your tilemap")

2: Get a pair of global coordinates. In your case (I think) that would be the location of the collision.

3: Convert the global position into tilemap local coordinates.

var local_position = tilemap.to_local(global_position)

4: Convert that local position into a tilemap grid position.

var tile_position = tilemap.world_to_map(local_position)

5: Get the ID number of the tile in that position.

var tile_id = tilemap.get_cellv(tile_position)

6: Get the name that goes with that ID in your tileset.

var tile_name = tilemap.tile_set.tile_get_name(tile_id)

I hope this helps.

(I’m assuming you have collision shapes on some of your tiles already, and detecting collisions is already working. I’m not very good with that part of the process, myself.)

Thank you very much! :wink:

Grizly | 2022-01-26 21:06

I’m glad that is what you needed! :slight_smile:

fatcat__25 | 2022-01-26 22:37

Any idea how to do it in Godot 4 ?

Omiod | 2023-03-03 10:01

I have not worked with Godot 4, so I can’t help you there, I’m afraid.

fatcat__25 | 2023-03-04 20:10

To do this in 4.0:

If you have the tile location as a vector2i, then you can grab the tile name using some Godot magic:

tile_location is a Vector2i of the cell location
local_tile_map is the TileMap that the cell is located in

var tile_data = local_tile_map.get_cell_tile_data(0, tile_location)
var tile_source = local_tile_map.get_cell_source_id(0, tile_location)
var tile_set = local_tile_map.tile_set
var tile_set_source = tile_set.get_source(tile_source)
var tile_name = tile_set_source.resource_name