How to spawn enemies every 3 seconds or so

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

I am trying to make a sciript that spawns enemies every 3 seconds or so but they either spawn out of screen or do not spawn at all. Scene begins with 3 of the same enemy.
I want them to spawn on X axis that the player is on.
I added a Timer child to the Main 2D node that scene plays on and added timeout signal that is connected to the Main 2D Node.

var Enemy = preload ("res://NPC.tscn")
func _on_EnemyTimer_timeout():
	var e = Enemy.instance()
	e.position = Vector2(-650.747, 373)

The position I have written is just above the player.
Also the NPC(enemy) is a scene itself but it is also in the res// folder because of the already 3 existing enemies in the scene.
Please help me on this one.

:bust_in_silhouette: Reply From: Zylann

With the timer you have pretty much done the work of spawning every N seconds, actually.
The position is hardcoded, so every new enemy will appear at the same place.

First, make sure your main 2D node (the root of the scene, I assume?) has a position of (0, 0). It’s important so there is no weird offset going on with the contents you spawn with global coordinates (or you could make the root a simple Node, instead of Node2D).

Next, in order to spawn enemies along the X axis of the player, you need to access the player. Then, add a distance to the X position, negative to be on the left, positive to be on the right.
Something like this?

var Enemy = preload ("res://NPC.tscn")

func _on_EnemyTimer_timeout():
	var player = get_node("Path/To/Player")
    var e = Enemy.instance()
    var pos = player.position

    if randf() < 0.5:
    	# On the left
    	pos.x -= rand_range(50.0, 200.0)
    	# On the right
    	pos.x += rand_range(50.0, 200.0)

    e.position = pos

I checked Transform and made sure that Node2D is on 0,0 after making it so everything else moves with it. It still does not work though. Is there a specific way I should set Timer settings?

xxxtlgxxx | 2020-03-24 20:46

Ooh, now that Autostart is open they spawn. Thanks a lot!

xxxtlgxxx | 2020-03-24 20:56