How to check for collision when instancing an object

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

Hi,

I’m still learning Godot, and I’m trying to create some sort of post-it board, with moveable and writeable post-its, etc.
I’ve been doing some researches, and I found this reddit post, with non-conclusive answers, which deals about kind of the same problem as I’m facing now.
I have set a button to spawn new post-its, and I want to check for objects overlapping with the newly instanced post-it, and if it is overlapping, I want to move it a little.
I use Area2D as root nodes of my post-it instances.

However, it seems that get_overlapping_areas() can’t be called before a certain time, and is then not really useful for me. If I check this function when instancing the post-it, it returns a blank array, even if it overlaps. Same if I check it during its _ready() function. It only returns overlapping areas if I call it after its instantiation, through a button or a timer. However, I’m reluctant at the idea of setting a timer for obvious reasons, and using a button is also not a great idea, because of the need of user input. In the reddit post, another solution proposed was to set a function checking every child of the main node, but I’m not happy with it because it will take much longer with a great number of post-it.

I hope a better solution exists to do what I want, and I hope you can help me! Maybe I’m just missing something, or approaching the problem from the wrong direction.

What is the code for instanciating nodes and searching for collisions?

Maybe you could try to skip some frames, instead of using timers.

var wait_frames = 100 # Or another amount you like..

_process(delta):
    if wait_frames > 0:
        wait_frames -= 1
        return

    # use  your get_overlapping_areas() logic here:
    # ...

And what about signals? Did you tried it as well?

RenenerG | 2019-02-24 23:21

:bust_in_silhouette: Reply From: eons

Since you do not have any physics running when instancing, the new object cannot know what is there.

Your only way to prevent placing elements on a busy place is to get the physics world space state (Physics2DDirectSpaceState) and use a shape cast to check if something is there.

You can get the state via get_world2d().state and then craft the queries you want for that.
See the reference Physics2DDirectSpaceState — Godot Engine (3.0) documentation in English for more details on what is available.

Some examples on the official documentation: