When we play games such as MMORPGs, it’s common to ask experienced players, “Where does this monster spawn?".
We call the ability to create new enemies and objects in the game’s world spawning. A spawner is an invisible position in the game’s world that creates instances of an object or monster. Spawning is the bread and butter of game development.
Here are some common uses:
- Spawning bullets from a gun
- Creating choreographed enemy waves
- Spawning particles
- Casting a spell from a specific point
The first thing to do is create a new scene with a Position2D as the root. We can see Position2Ds in the Editor, but they’re invisible for players. Let’s name it Spawner2D.
Attach a new script to the Spawner2D and export a new PackedScene variable. This variable will hold the object scene that will spawn.
extends Position2D export var spawn_scene: PackedScene
Let’s work on the spawning logic. We want to create new
spawn_scene instances at the Spawner2D position, then add them as its children. There’s a problem, though; when the Spawner2D moves, its children also move. To prevent this, we need to
set_as_toplevel(true) every time we instance a new
func spawn(_spawn_scene := spawn_scene) -> void: # Creates a new instance of the _spawn_scene var spawn := _spawn_scene.instance() as Node2D add_child(spawn) # Prevents the Spawner2D transform from affecting the new instance spawn.set_as_toplevel(true) # Move the new instance to the Spawner2D position spawn.global_position = global_position
And that’s it!
You can mix the Spawner2D with other nodes to achieve many exciting systems—especially when combined with an AnimationPlayer since you can animate the
In our project’s demo scene, we used two Spawner2Ds. One spawns bullets from the player’s gun, and the other spawns enemies. The EnemySpawner2D uses an animation to dictate where and when to create new enemies. The Player’s BulletSpawner2D triggers its
spawn() based on the player’s input.
Our tutorials are the result of careful teamwork to ensure we produce high quality content. The following team members worked on this one: