Spawn multiple enemies at random spots on Path2D

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

I have a “Main” node and associated with some menu buttons, one of 2 methods gets called. SpawnBlue, SpawnRed.

I want to spawn multiple Blue items along a Path2D
------BlueGuy *added as child in code below *

At top before ready() set this:

export var BlueGuyNode = preload("res:///Scenes/BlueGuy.tscn")

Then triggered by a button click, this gets called.

 func SpawnBlueGuy():
      var BlueGuy =  BlueGuyNode.instance()	
      var blueGuyPath = get_node("BluePath2D/BluePathFollow2D")
      blueGuyPath.offset = 0

What I am trying to get happen is that when the button is clicked the first time, BlueGuy gets spawned and begins walking around his path. Let’s just say it is a circle and the starting position is 12 0’clock.

enter image description here

So next, let’s say when he is at the 4 0’clock position and I click the button again, a second BlueGuy should spawn at 12 o’clock

enter image description here

What is happening, though, is that when the button is clicked for the second time, BlueGuy #1 gets jumped back to the starting position of the circle and BlueGuy #2 gets added in the same position…so it looks like only 1 guy is there even though there are two.

And on the BlueGuy code, in ready() I am grabbing the BlueGuy path like this:

blueGuyPath = MainScene.get_node("BluePath2D/BluePathFollow2D")

and the movement is handled in _process like so:

func _process(delta: float) -> void:
	blueGuyPath.offset += 50 * delta

How can I update this code to let BlueGuy #1 keep his current position when the button is clicked a second time and BlueGuy #2 gets added to the path (at start position)? This happens even if I click Add 20 times (…I put a counter to test whether or not there were indeed multiple BlueGuy items and there is)

2D scenes

Note that physics_process() is the recommended way to handle movement, as it runs in a separate thread and should not be influenced by fps fluctuations.

skysphr | 2022-01-25 08:44

:bust_in_silhouette: Reply From: skysphr

A PathFollow2d can only have one offset (or unit_offset) at a time, so reusing the same node for multiple blue guys would exhibit the described behaviour (also it should technically make the thing go faster with each added child). To achieve the desired effect you will need to create a separate PathFollow2d for each enemy spawned.

Thank you, I appreciate the info. I’ll try either multiple pathfollow2d objects or see if I can come up with a different approach…maybe a navigation style node.

corbybender | 2022-01-25 13:05

If you really want to avoid using multiple PathFollow2d objects you can implement the mechanic yourself by calling the path’s curve.interpolate_baked() with varying degrees of offset.

skysphr | 2022-01-25 14:16