Detect which tile an Area2D is overlapping with

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

My unit scene has an Area2D “Sensorium” with a CollisionShape2D. I use the body_shape_entered signal on the Area2D to detect overlaps. This works fine with other units because I can get their positions via the body parameter and make the unit react accordingly.

However, if the CollisionShape2D overlaps with a tile in a tileset, the body parameter is the TileMap node, and gives no information about what specific tile is overlapping.

func _on_Sensorium_body_shape_entered(body_id, body, body_shape, area_shape):
         print(body_id, ", ", body, ", ", body_shape, ", ", area_shape)

When overlapping with a tile, the above code prints:

1221, [TileMap:1221], 3, 0

As you can see, the above signal does not help to get the tile the Sensorium Area2D’s CollisionShape2D has overlapped with. It only tells me the tilemap it overlapped with.

I am not interested in physics collision. I am interesting in detecting if the unit is close to tile(s) so the unit can apply a steering force to move it away from the tile(s) before it gets near to the tile(s).

How do I detect which tile an Area2D’s collision shape is overlapping with?

[edit: clarity]

:bust_in_silhouette: Reply From: clemens.tolboom

You can scan for the tile/cell using world_to_map

var unit_location:Vector2 = unit.global_position
var cell:Vector2 = tilemap.world_to_map(touch_location)

You may have to consider the position of your tilemap. See also this tilemap question/answer