godot 4.3 courses
Start below launch price for a limited time
Now in Early Access!

Spawning

beginner

By: Henrique Campos - July 24, 2020

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

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

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.

Made by

Our tutorials are the result of careful teamwork to ensure we produce high quality content. The following team members worked on this one:

Henrique Campos

Tutor

Johnny Goss

Tutor

Related courses

Banner image

Learn 2D Gamedev with Godot 4 $99.95

Built on the success of GDQuest’s bestselling course, this Godot 4 course uses cutting edge ed-tech to teach the fundamentals of game development over 19 modules packed with interactive exercises.

Banner image

Learn 3D Gamedev with Godot 4 $99.95

This long-awaited course adds a third dimension to the knowledge you pick up in Learn 2D Gamedev. By the end of it, you will have the skills to build your own 3D game.

Related tutorials