Checking if space is empty for spawning using space state

TwoheadedFetusTwoheadedFetus Posts: 1Member

I'm trying to spawn area2Ds in random places on the screen periodically, only thing I'm having a problem with is making sure that they don't spawn one on top of each other. I'm trying to use a space state query but my code doesn't work. Heres the code in Gdscript:

func _on_Timer_timeout():

    var virusNode = virus.instance()

    var space_state = get_world_2d().get_direct_space_state()

    var query =

    var result = [1]

    while result.size():
        var x = rand_range(virusNode.get_child(0).get_texture().get_width()/2, Globals.get("display/width") - virusNode.get_child(0).get_texture().get_width()/2)
        var y = rand_range(virusNode.get_child(0).get_texture().get_height()/2, Globals.get("display/height") - virusNode.get_child(0).get_texture().get_height()/2)
        virusNode.set_pos(Vector2(x, y))
        result = space_state.intersect_shape(query)


the result array is always empty, even when the spawned node intersects another one. The spawned nodes have collisionBody2D under the area2D too. the query also recognises the shape as a circle correctly, and gets transform coordinates. This is part of the script that attaches to the root node of the scene.


Tags :


  • Ace DragonAce Dragon Posts: 220Member
    edited August 2018

    You could try creating a Rect2D variable if the size is known ahead of time. You could have an array of them that represent the locations of your objects (growing and shrinking the array when viruses are added and removed).

    What I would do then, when a space is randomly chosen, you check to see if the chosen coordinates is within a Rect2D (iterating through the array and doing said check for each one). If it is. don't add another child object and create a new number instead.

    Don't have example code for this since I'm not working in 2D, but look up the Array class and it should tell you everything about making the list.

  • salamandersalamander Posts: 1Member
    edited October 2018

    For reference, Physics2DDirectSpaceState methods don't detect collisions with Area2D nodes. You need to change your Area2D nodes to one of the three PhysicsBody2D node types.

Sign In or Register to comment.