0 votes

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,

Godot version 3.3.2
in Engine by (23 points)

1 Answer

0 votes
Best answer

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.

by (290 points)
selected by

Thank you :)

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.