Getting tile positions

Godot Version

4.5

Question

Hi, I was wondering if there is a way to get the positions of all tiles within the bounds of an area2D and store them into an array?

There is. Use area’s body_shape_entered signal. The first argument of this signal can be passed to TileMapLayer::get_coords_for_body_rid().

The tiles will need to have a physics layer set up for collision to properly register.

1 Like

Could you give me an example in code please?

func _on_area_2d_body_shape_entered(body_rid, body, body_shape_index, local_shape_index):
	print(tile_map_layer.get_coords_for_body_rid(body_rid))

Its printing the tile positions but they all came out as (0, 0).

Make sure to set up the colliders properly.

Ok so I adjusted the collision and the collision shape is 64 x 64 pixels which is the equivalent of 16 tiles and here is the return I got.

(0, 0)
(-1, 0)
(-1, 0)
(-1, -1)
(0, -1)
(0, 0)
(0, 0)

Do you think the collision shape of the character body 2D I attached the area 2D to is causing interference?

Depends on your setup. Try to make a simple proof of concept setup in a fresh empty project.

Ok I made a new scene and put the entity I created in onto a fresh tilemap layer and now the game seems to have divided the entire tilemap layer into quarters and the entity is now just reading the coordinates of which quarter it is in rather than the coordinates of the individual tiles.

You’ll need to share your setup and your code. Otherwise it’ll be very hard to tell what’s happening.

extends CharacterBody2D

@onready var visionArea = $VisionArea
@onready var tile_map_layer = $“../Tiles/TileMapLayer”

func _on_vision_area_body_shape_entered(body_rid: RID, body: Node2D, body_shape_index: int, local_shape_index: int) → void:
var coords = tile_map_layer.get_coords_for_body_rid(body_rid)
print(coords)

Here’s a screenshot of the main scene being played. The tiles are supposed to be gray.

So where’s the problem? You have 4 tiles that collide with the area and the code prints all 4 of them as it’s supposed to.

Btw you have some other errors reported by the engine. You should correct those.