0 votes

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

Godot version 3.2
in Engine by (195 points)
recategorized by

1 Answer

+3 votes

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.

by (3,257 points)

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.