+1 vote

The problem with the Rays .
I get the output array that is sorted by id.

I need to get in the order in which they enter the ray.

Please help me.

in Engine by (81 points)

Which code did you used? Raycasts return one element, not an array.

var space_state = get_world_2d().get_direct_space_state()

var segment = SegmentShape2D.new()

segment.set_a(get_pos())
segment.set_b(get_pos() + line)

var query = Physics2DShapeQueryParameters.new()
query.set_shape(segment)
query.set_exclude([self])   
space_state.intersect_shape(query, 10)

1 Answer

+1 vote

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
class HitSorter:
    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())

func whatever():
    # ...

    var hits = space_state.intersect_shape(query, 10)
    var sorter = HitSorter.new()
    sorter.origin = segment.get_a()
    hits.sort_custom(sorter, "sort_hits")
    # 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

by (27,902 points)

thanks for the help.
I solved the problem simply sorting the array.

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 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 webmaster@godotengine.org with your username.