Detect Sprite overlapping

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

Hello Godot community,

I have a simple Node2D containing Sprites
The sprites are images that I spawn with a random position at startup.
Using random for the spawn opens the overlapping door, some sprites can overlap on others (in this case I want to generate another random position). How can I prevent that ? (without going into some crazy mathematics)
I tried collision, but this doesn’t work at creation time so it won’t help.

Any other ideas how I can do this elegantly ?

Thank you,

:bust_in_silhouette: Reply From: gioele

Without using complex maths or using Area2D nodes I think the best way is checking the distances.

Since they are Node2D they have global_position property.
When generating them you have to add them to the scene but I suggest you to keep track of them using an array.

As soon as you create a new node, iterate through all existing sprites (stored in the array)
and check if sprite.global_position.distance_to(existing_sprite_pos) is < min_distance.

If it is less that a given minimum distance, create a new position and try again.

It may not be the best solution from a computational point of view but it also depends on the size of your problem.

Thank you :slight_smile:

Seli | 2021-06-08 19:32