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

Ultimate Godot course bundle 235$

This ultimate bundle gives you access to ALL our current and future Godot courses, at a discount. It’s like a lifetime membership.

Banner image

Godot secrets bundle 150$

A bundle with our four secrets courses at the price of three! It contains 2D Secrets, Shader Secrets, VFX Secrets, and PCG Secrets.

Related tutorials

No questions yet

Got a question or feedback regarding this guide?
Please use the form below.

Enter your email to get notified when someone replies to your comment.
We encrypt your addres with a strong 256-bit AES encryption.
We'll only use your address for notifications. You can unsubscribe anytime.