Spawning
2020/07/24
- Type
- Learning Resource
- Format
- Tutorial
- Version
- Godot 3.x
- Code
- MIT
- Game Assets
- CC BY-NC-SA
- All else
- 2016-2026, GDQuest© - All rights reserved
- Created
- Updated
- 2020/07/24
- 2020/07/24
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: PackedSceneLet'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_positionAnd 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.
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.
Get help from peers and pros on GDQuest's Discord server!
20,000 membersJoin ServerThere are multiple ways you can join our effort to create free and open source gamedev resources that are accessible to everyone!
Sponsor this library by learning gamedev with us onGDSchool
Learn MoreImprove and build on assets or suggest edits onGithub
Contributeshare this page and talk about GDQUest onRedditYoutubeTwitter…
Site in BETA!found a bug?