How to spawn something, inside a node(like Area2d)

Godot Version

latest version

Question

Im trying to make an Enemy Node(I alr programmed its instantiation), to spawn inside a node(something like Area2d), so then, I can make the Enemy Spawn around a border, instead of just using randi_range

An Area2D does not spawn anything by itself, but you can use its CollisionShape2D as the spawn region.

For example, with a RectangleShape2D:

@export var enemy_scene: PackedScene
@onready var spawn_shape: CollisionShape2D = $CollisionShape2D

func spawn_enemy() -> void:
    var rectangle := spawn_shape.shape as RectangleShape2D
    var half_size := rectangle.size * 0.5

    var enemy := enemy_scene.instantiate() as Node2D
    get_tree().current_scene.add_child(enemy)

    var random_point := Vector2(
        randf_range(-half_size.x, half_size.x),
        randf_range(-half_size.y, half_size.y)
    )

    enemy.global_position = spawn_shape.to_global(random_point)

You can resize the CollisionShape2D in the editor to visually define the area where enemies are allowed to spawn.

Glad that help you!

Thanks huge help, ill try to get help from others to understand parts of the code since im kinda learning gdscript, nonetheless thnk you

Glad to help you !