The main issue with raycasts is they stop after one hit. There's a trick involving the exclude parameter, but it means multiple raycasts (one for each object the ray intersects).
Godot 4 has added ShapeCast2D, which lets you do an immediate overlap test with multiple results at once (it gives you an array of every overlapped object).
In Godot 3.x, one way to do it is intersect_shape: https://docs.godotengine.org/en/stable/classes/class_physics2ddirectspacestate.html#class-physics2ddirectspacestate-method-intersect-shape
You call it with a shape and it gives you an array of every overlapped shape.
Here's a simple little test I made:
extends Sprite
export var shape:Shape2D
var param = Physics2DShapeQueryParameters.new()
func _ready():
param.collide_with_areas=true
param.collide_with_bodies=true
param.set_shape(shape)
func _process(delta):
param.transform = transform
var space_state = get_world_2d().direct_space_state
var res = space_state.intersect_shape(param)
if res.size()>0:
print(res.size())
I gave the shape property a rectangle shape of about 400x10 size.
If there are any bodies/areas overlapped with the rectangle (which I move to the player object using the param.transform = transform bit) it returns them all. I then printed how many were detected (but you could loop over them instead).
The intersect only happens when you call intersect_shape, so you can control when it is checked.