How do you spawn more enemies and make them fall randomly from certain y axis in godot 2D?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By KripC2160
:bust_in_silhouette: Reply From: njamster

You’re not overly specific here, so I’ll assume (based on the tags of the question) that your enemies are of type KinematicBody2D and have a script attached to them which makes them fall down every frame:

extends KinematicBody2D

const GRAVITY = 9.8 # pixels per second 

var velocity = Vector2.ZERO

func _physics_process():
    velocity.y += GRAVITY * delta

Now to instance your enemy scene from your main-scene, you would attach a script to your main-scene as well, containg something like this:

const SCREEN_WIDTH = 1920
const SCREEN_HEIGHT = 1080

func _ready():

func spawn_enemy():
    var new_enemy = load("<PathToYourEnemyScene>").instance()
    new_enemy.position.x = randi() % SCREEN_WIDTH
    new_enemy.position.y = randi() % SCREEN_HEIGHT

If you haven’t already, I’d highly recommend working through this tutorial.