Is it possible to cast a ray that doesn't stop at the first object?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By mbalint
:warning: Old Version Published before Godot 3 was released.

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!

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

eons | 2017-01-28 19:49

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.

mbalint | 2017-01-28 20:50

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

mbalint | 2017-01-28 20:55

:bust_in_silhouette: Reply From: avencherus

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)