+1 vote

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)
    add_child(e)

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.
Thanks.

in Engine by (22 points)

1 Answer

+2 votes
Best answer

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)
    else:
        # On the right
        pos.x += rand_range(50.0, 200.0)

    e.position = pos
    add_child(e)
by (27,954 points)
selected by

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?

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.