Challenge - Spawn Enemies

The challenge requested to add a series of markers as points to be used to spawn enemies. While this is the approach used by the teacher I decided to apply the random spawn approach.

I, too, also have made the enemy spawner scene but instead of using the markers I have taken the viewport screen size and used the randi_range function to spawn the ships in a random way.

Here is the script:

class_name EnemySpawner extends Node2D

@onready var _screen_x_size = get_viewport_rect().size.x
@onready var _spawn_timer = get_node("SpawnEnemyTimer")
@onready var _enemy = preload("res://scenes/enemy.tscn")

func _ready():
	_spawn_timer.connect("timeout",_spawn_enemy)

func _spawn_enemy():
	# Instantiate the enemy
	var enemy_ship = _enemy.instantiate()
	# Change the position
	enemy_ship.global_position = Vector2(randi_range(100, _screen_x_size - 100), -125)
	# Add the enemy
	add_child(enemy_ship)

Final result:
out

2 Likes

Privacy & Terms