gdscriptgodot4

How to get position of nodes(marker2d) in a gruop / GODOT 4.2.2


I would like to spawn "enemy" on the position of every marker2d. Those markers are in a group called "enemies". I would like to know if its possible to spawn an "enemy" on every marker by just looking at the group.

I tried almost every solution online and I failed. From creating a new function to just get the position of nodes in a group, to changing markers2d into other nodes, to creating new variables... In short im trying to avoid defining vector2 for each marker2d or using $nodes everywhere. I would like to know if this is possible by just looking at groups.


Solution

  • This should be what you’re looking for:

    for spawnpoint in get_tree().get_nodes_in_group("enemies"):
        if spawnpoint is Marker2D:
            spawn_enemy(spawnpoint)
    

    Or if your Marker2Ds expose the spawn_enemy() function you could do this:

    get_tree().call_group("enemies", "spawn_enemy")
    

    https://docs.godotengine.org/en/stable/tutorials/scripting/groups.html

    Try this, maybe? You’re not going to need func spawn_enemy().

    func _ready():
        for spawnpoint in get_tree().get_nodes_in_group("enemies"):
            if spawnpoint is Marker2D:
                var enemy = enemy_scene.instantiate()
                main.add_child(enemy)
                enemy.position = spawnpoint.position