How do you detect if an Area2D overlaps another Area2D at time of instantiation?

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

How do you detect if an Area2D is within another Area2D when it is first instantiated?

It seems intuitive to use get_overlapping_areas() within _ready() to do this but it doesn’t work because get_overlapping_areas() uses the physics engine, and when a node is first instanced, physics will not actually be ready.

Broken code:

func _ready():
     print(get_overlapping_areas()) # doesn't print overlapping areas

This is a common use case I find myself in but I’m never sure of the correct way to approach it. I’ve solved it using this:

func _ready():
     yield(get_tree(), "idle_frame") 
     print(get_overlapping_areas()) # does print overlapping areas

But the solution seems inelegant and hacky. It may also not be acceptable because there may be initialization (setting certain properties etc) that you want for the node that is dependent on what Area2Ds it overlaps with and that you want to have finished before idle_frame.

What are people’s preferred ways to approach this?

:bust_in_silhouette: Reply From: rossunger

you can use call_deferred( "get_overlapping_areas") to defer the function call to the end of the frame. Look up “call_deferred” for more info :slight_smile:

Thanks but that doesn’t work. get_overlapping_areas is still returning an array of length 0.

gogodot77 | 2022-02-06 01:02

maybe you could use the instantiated area2D’s area_entered signal? and have it as a one-shot?

rossunger | 2022-02-06 01:07

The area_entered signal will only fire once fully instantiated (i.e., after _ready) as far as I understand it. But I need some setup for the node before that.

gogodot77 | 2022-02-06 01:17

Could you share some more about what you’re trying to do that needs to be done on _ready?

I find when I encounter obstacles like this it’s usually because I’m trying to solve a problem in a non-godot way when there might be a more elegant godot-style solution…

rossunger | 2022-02-06 01:24

Ok I’ve got something working by trying your area_entered signal suggestion (against my idea that it wouldn’t work). So thank you for the suggestion.

Of course, it’s opened up a whole new can of worms which makes me think I’m working against Godot in some way. If I have the mental fortitude I’ll try and articulate the problem more clearly and post again.

Thanks for your help.

gogodot77 | 2022-02-06 02:46

Please do! I’m very curious to hear your use-case :slight_smile:

rossunger | 2022-02-06 13:39

Thanks for your interest. I’ve created a new question here: How do I do initial set up when get_overlapping_areas() returns an empty array in _ready? - Archive - Godot Forum

gogodot77 | 2022-02-06 23:00