A more traditional spawning pattern

Looking to games like R-Type, Gradius, etc, we see enemies show up in packs, flying in parabola all in a line. While I have coded the parabola function in to the enemies, what I wanted to show was the code for an enemy spawner that spawns enemies in packs, with a pause in between.

extends Node2D

@export var wave_size: int = 6
var spawn_position_array
var remaining_in_wave = wave_size
var enemy_ship_scene = preload("res://scenes/enemy_template.tscn")
@onready var release_target = get_node("SpawnPositions/SpawnPosition01")
@onready var wave_release_timer = $WaveSeparatorTimer
@onready var ship_separator_timer = $ShipSeparatorTimer

var random = RandomNumberGenerator.new()

func _ready():
	random.randomize()
	var spawn_positions = get_node("SpawnPositions")
	spawn_position_array = spawn_positions.get_children()

func _on_ship_separator_timer_timeout():
	# If there's ships left in the wave,
	if (remaining_in_wave > 0):
		#Instantiate a ship as a child to the current release target
		var enemy_ship_instance = enemy_ship_scene.instantiate()
		release_target.add_child(enemy_ship_instance)
		#Decrement the ships remaining in the wave and start the timer for the next check
		remaining_in_wave -= 1
		ship_separator_timer.start()
	else:
		# If there's no ships left in the wave, reset the wave and start the timer for the next squad.
		print("Wave done.")
		remaining_in_wave = wave_size
		wave_release_timer.start()


func _on_wave_separator_timer_timeout():
	print("New wave.")
	# Choose a random node from the release target array for use during the next squad's release
	release_target = spawn_position_array[random.randi_range(0,spawn_position_array.size()-1)]
	# Start the timer for squad separation
	ship_separator_timer.start()


Enjoy!

3 Likes

Thanks for sharing. I was also thinking of doing something like this. To get the enemy formations in shapes I was considering having the spawner move off-screen to produce the shape. I am hoping that I can simply animate the spawner position.

Privacy & Terms