0 votes

I would like to procedurally spawn objects which are basically Area2D nodes with circular collision shapes. This Areas should not overlap.

I am not cure how to do check if certain circular surface of the scene is free of existing collision shapes.

Godot version 3.2.3
in Engine by (31 points)

1 Answer

+1 vote
Best answer

Using math ;)
Assuming your Area2D is it's own scene with CollisionShape2D as its child:

var area_2d_scene = preload("res://default_env.tres")
func spawn_units():
    var objects_spawned = []
    var num_to_spawn = 10
    while objects_spawned.size() < num_to_spawn:
        var potential_spawn_location = get_random_vector_within_bounds()
        var can_place = true
        for object in objects_spawned:
            var object_radius_squared = pow(2 * object.get_node("CollisionShape2D").shape.radius, 2)
            if potential_spawn_location.distance_squared_to(object.position) < object_radius_squared:
                can_place = false
        if can_place:
            var new_object = area_2d_scene.instance()
            new_object.position = potential_spawn_location

Few things to note: using a while loop is generally inadvisable here. You would need to implement get_random_vector_within_bounds(). This assumes all objects have the same radii.

by (3,710 points)
edited by

Thank you for your help!

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 Frequently asked questions and 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.