get a list of objects which raycast crossed

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

The documentation I found only.
What raycast object returns 1.

How to get a list of objects which raycast crossed?

:bust_in_silhouette: Reply From: Zylann

Instead of casting a ray, use a SegmentShape2D:

# Do this inside _fixed_process() or _integrate_forces()
func segment_cast(begin_pos, end_pos):
	var space_state = get_world_2d().get_direct_space_state()
	
	var segment = SegmentShape2D.new()
	segment.set_a(begin_pos)
	segment.set_b(end_pos)
	
	var query = Physics2DShapeQueryParameters.new()
	query.set_shape(segment)
	query.set_exclude([self]) # If you want to exclude the object casting the segment
	query.set_layer_mask(GROUND_MASK) # Set the collision mask you want, or none if you want to hit anything
	
	var hits = space_state.intersect_shape(query, 32)
	return hits

not sure if you’ll read this, but does this happen to be quite inefficient if called maybe 100 times a frame?

Even if I store the space_state, segment and query?

manglemix | 2020-04-19 09:12

Caching the shape and query objects may help.

Zylann | 2020-04-19 13:44

:bust_in_silhouette: Reply From: linuxfree
    func check_ray_collider():  
        var ray = get_node("RayCast")
        if ray.is_colliding():
            
            var object = ray.get_collider()
    
            if object extends RigidBody or object extends StaticBody:
             
                print("Object Collider", object.get_name())

   # run function check_ray_collider() in _fixed_process(dt)
and you can add KinematicBody too.

tested in 3D method