Correct way to check overlapping areas immediately (in 2D)

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By SacrificerXY

I want to get a list of Area2Ds overlapping a certain area/shape immediately without waiting for a physics update or the next frame. I want to do this purely in GDScript.

What I tried is instancing an Area2D scene which then triggers signals. It is then removed in the next frame. The problem is that I’m not quite sure when these triggers will fire. I want to know exactly when these triggers happen since they modify the game state. I don’t want my aoe damage to inflict damage the next frame instead of immediately.

:bust_in_silhouette: Reply From: SacrificerXY

I settled on using Physics2DDirectSpaceState.intersect_shape:

# initialize parameters for query
var params = Physics2DShapeQueryParameters.new()
params.set_shape(shape) 
params.transform = # set position/rotation/scale of shape
params.collision_layer = # collides with objects in same layer
params.collide_with_bodies = false
params.collide_with_areas = true

# do query
var space_state = get_world_2d().direct_space_state
var query_results = space_state.intersect_shape(params)
for result in query_results:
    var actual_collider_object = result.collider
    # do stuff

I only tested this inside a _physics_process context. The collision_layer parameter seems to also act as a mask. So you can add different layers together to allow checking in multiple layers. I’m not sure though.