Godot - Sort group nodes by distance
This is how to sort group nodes by distance in order using GDScript in Godot 4.
I created a sort_group_nearest()
using sort_custom()
to sort group nodes in order of distance.sort_group_nearest()
has the following characteristics:
- Specify any group name as an argument
- Returns nodes sorted by distance from itself
func sort_group_by_nearest(group):
var nodes = get_tree().get_nodes_in_group(group)
nodes.sort_custom(func(a, b):
return a.global_position.distance_to(global_position) < b.global_position.distance_to(global_position)
)
return nodes
func _ready():
var enemies = sort_group_by_nearest("enemies")