Instancing new kinematic body in random position

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

Hi all,
I’ve been searching the net for a few hours but found nothing, and I thought this should be pretty common:

I’m instancing 20 bodies with a collision polygon, with a random position.
In case I hit a previous instance (or any of the other bodies that appear on screen), I need to generate a new position.
I assume that because It’s spawning a new object and not moving it, move_and_collide doesn’t work properly.

Can you help?

Note: The object is a Kinematicbody2D with a sprite and a CollisionPolygon2D in the shape of a banana…

var banan #future instance Banana
var banana_temp_pos
var small_distance_flag # Flag is 1 if distance too small
# Run from 0 to 19
for i in range(20):
    small_distance_flag = 1
    banan = Banan.instance()
    add_child(banan)
    # Generate temp position while distance from existing objects is too small
    while small_distance_flag == 1:
        # Generate position for banana
        banana_temp_pos = Vector2(randi() % int(get_viewport().size.x-40) + 20 ,randi() % int(get_viewport().size.y-20))
        banan.position = banana_temp_pos
        if !banan.move_and_collide(Vector2(0,0), false, true, true ): # test move here: does banana collide anything?
            print(banan.get_world_2d().direct_space_state.get_rest_info().size)
            small_distance_flag = 0
        else:
            print("happens")
:bust_in_silhouette: Reply From: lucaslcode

Just use position to set the position without physics when placing it.

I did (see in the code I presented),
but when I generate a random position, I don’t know if the place is already occupied by another object.
And it’s not only the point I generated, but rather all the shape of the object.

I had a previous try when I manually calculated distance between the random positions, but it only calculates the distance between objects’ centers, and the objects aren’t round so they still overlap (or I can make the distance far enough that they never overlap but then it’s a lot more restricted then I wanted)

segold | 2020-03-30 06:01