How get the node closest to my position?

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

I have a main node and I want to take the node closest to it, how do I do this, I have no idea

:bust_in_silhouette: Reply From: Magso

I wrote this function to put a singleton

func find_closest_or_furthest(node: Object, group_name: String, get_closest:= true) -> Object:
	var target_group = get_tree().get_nodes_in_group(group_name)
	var distance_away = node.global_transform.origin.distance_to(target_group[0].global_transform.origin)
	var return_node = target_group[0]
	for index in target_group.size():
		var distance = node.global_transform.origin.distance_to(target_group[index].global_transform.origin)
		if get_closest == true && distance < distance_away:
			distance_away = distance
			return_node = target_group[index]
		elif get_closest == false && distance > distance_away:
			distance_away = distance
			return_node = target_group[index]
	return return_node

So the code can just be

singleton.find_closest_or_furthest(self, "group") #finds closest
singleton.find_closest_or_furthest(self, "group", false) #finds furthest

If you’re in 2D change global_transform.origin to global_position.

The way it works is by iterating through the node group and checking if the next vector length distance is less/more than the last one and setting a variable to that lower/higher value and assigning the node the iterator is referencing.

You can write more simple:

if (get_closest && distance < distance_away) || (!get_closest && distance > distance_away):
        distance_away = distance
        return_node = target_group[index];

And you dont need else

CHROM | 2022-05-04 22:56