Find the closest distance

Godot Version = 3

Question

I don’t know what’s wrong with the code.
what i want to do is: find out which node has the smallest in world distance to the Vector3 input.

func find_closest_node(position: Vector3) → int:
var closest_node_id = -1
var closest_distance = float(‘inf’)

for child in get_children():
	var node = child as Node
	if node is Node:
		var distance = position.distance_to(node.global_transform.origin)
		if distance < closest_distance:
			closest_distance = distance
			closest_node_id = node.node_id
return closest_node_id

What are you trying to do, specifically, and what is happening instead?

the function is for my own navigation system where i can place nodes in the world. each of these nodes has an ID and a list of IDs of other nodes it is connected to. the idea of the system is that i can make grid systems or similar without any restrictions.
the function mentioned has the task of converting the position in the world into a node ID. (so i can calculate stuff and place the character at the world position of another node)

the problem is that the function returns the fallback value: -1.
i have already tried several things to solve the problem, without success

Are the nodes you want to check distance to definitely immediate children of the node where this function is being called, so they will be included in the get_children list?

What happens if you try replacing float('inf') with INF? Or a large finite number like 1000000? Does the behavior change at all?

I have exactly 3 scripts in this system:
-nav_node #is a node with the corresponding data
-nav_maneger #it contains the genate function and has all nav_nodes as children
-character #it accesses the functions from nav_maneger to do stuff

Well Well
gg you fix it…

with float(999999) it works

thank you. you are the best
(I guess I’m really stupid xd)

1 Like

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