Finding neighbours in a control grid with distance_to

Godot Version



I am having trouble understanding issues related to distance_to (2d).
I have a functions that check if the tiles on the grid are neighbours. I run the function in the tile script, the tile node is a control node. The tiles are instantiated in a grid, so I refer to them via getting the grids’ children.

this is the function:

var neighbours : Array

func findNeighbours():
	var tileArray = grid.get_children()
	for _tile in tileArray:
		var tileOffset = position.distance_to(_tile.position)
		if tileOffset < size.x +20 and tileOffset > 0:

now, If I call this function at _ready, and I print the neighbours, the array is empty.
However if I call this function in can_drop_data(), as soon as I hover over the tile, it prints the correct neighbours.

func _can_drop_data(at_position, data) -> bool:
		var can_drop: bool = data is Node 
		return can_drop

I don’t seem to understand where the problem is. Is related to the cursor’s position? How can I write it so it work without me interacting with it (for exaple, dragging things over it)?

I’m assuming grid is a TileMap node? To which node is the script with the findNeighbours function attached to? This is relevant information here, since your code uses that node’s positionand size to determine if something will be added to the neighbours array!

It might simply be that some of those positions aren’t properly initialized yet, when _ready is run. Have you tried findNeighbours.call_deferred() yet?


Thank you for the suggestion, it took a couple of step more and it solved it.

The Grid is not a TileMap node, it is a GridContainer . It is the child of a MarginContainer, which in turn is the child of a generic Node2D .
findNeighbours is attached to the tile node, which is a ColorRect.

When findNeighbours.call_deferred() was called from the tile, it still returned an empty array. However I called it deferred from the Grid’s parent node:

func _ready():

func theNeighbourhood():
	tiles = grid.get_children()
	for i in tiles:

and it worked! Thank you a lot for the suggestion.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.