0 votes

I know the basic Physics2DDirectSpaceState.intersect_ray() and RayCast2D class, but those stop at the first object they hit. Is there any built-in way to get all object intersecting a ray?
Thanks!

in Engine by (14 points)

Then you don't want to cast a ray but maybe to use a (area with) segment shape and checking overlap.

Thank you! I found out that there is a shape type called RayShape2D. I added this to an Area2D checked the overlapping objects, then got the contact points with collide_and_get_contacts. It works ok.

No, actually, I used SegmentShape2D instead of the RayShape2D.

1 Answer

0 votes

I don't believe so. Only intersecting shapes hold a list of collisions.

What I've done in the past for rays is use a loop and a list, though it may not be very optimal. The loop is for testing multiple times, and the list is outside the loop collecting the references.

Inside the loop you cast the ray with the list as the exceptions. The first time through there are none, so it hits the first object. Then you add each found object to the list, and on the next iteration they're excluded from the raycast.

Something like this:

var hits = []

while(true):

    var ray_result = space.intersect_ray(ray_origin, cast_to, hits)

    if(ray_result.empty()): break # It's a dictionary so test .empty()
    hits.append(ray_result.collider)

print(hits)
by (5,206 points)
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.