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.