Spawning

2020/07/24

Type
Learning Resource
Format
Tutorial
Version
Godot 3.x
Subject Tags
    Code
    MIT
    Game Assets
    CC BY-NC-SA
    All else
    2016-2026, GDQuest© - All rights reserved
    Created
    2020/07/24
    Updated
    2020/07/24

    Spawning

    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:

    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.

    updates / code patches

    Become an Indie Gamedev with GDQuest!

    Don't stop here. Step-by-step tutorials are fun but they only take you so far.

    Try one of our proven study programs to become an independent Gamedev truly capable of realizing the games you’ve always wanted to make.

    Nathan

    Founder and teacher at GDQuest
    • Starter Kit
    • Learn Gamedev from Zero
    Check out GDSchool

    You're welcome in our little community

    Get help from peers and pros on GDQuest's Discord server!

    20,000 membersJoin Server

    Contribute to GDQuest's Free Library

    There are multiple ways you can join our effort to create free and open source gamedev resources that are accessible to everyone!

    Site in BETA!found a bug?