Intersecting a segment will return unordered results because I guess it doesn't usually matter, as well as shape intersection.
On the other hand, you can use a raycast, which will return the first encountered object.
If you really need all returned objects to be sorted by distance, you can put them in an array and sort them with whatever predicate you want:
# Note: using a class is not mandatory, you can also
# use the script itself with `self` and a function,
# however I find it cleaner
var origin = Vector2()
func sort_hits(hit_a, hit_b):
# Hmmm... no position in hits?
return origin.distance(hit_a.collider.get_pos()) < origin.distance(hit_b.collider.get_pos())
var hits = space_state.intersect_shape(query, 10)
var sorter = HitSorter.new()
sorter.origin = segment.get_a()
# Now they are ordered
However I also realize that the results of intersect_shape() don't contain the position of the intersections, so I used
hit.collider.get_pos(), which is less precise but should at least order the objects. This could be a good thing to ask on Github :p