
Godot Game Loop Waves
- 134 installs
- 454 repo stars
- Updated July 28, 2026
- thedivergentai/gd-agentic-skills
Helps with ai & agent building tasks during AI-assisted development.
About
godot-game-loop-waves is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted coding.
- godot-game-loop-waves
- AI & Agent Building
- AI-coding skill
Godot Game Loop Waves by the numbers
- 134 all-time installs (skills.sh)
- +19 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #3,615 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/thedivergentai/gd-agentic-skills --skill godot-game-loop-wavesAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 134 |
|---|---|
| repo stars | ★ 454 |
| Last updated | July 28, 2026 |
| Repository | thedivergentai/gd-agentic-skills ↗ |
What it does
Helps with ai & agent building tasks during AI-assisted development.
Files
Wave Loop: Combat Pacing
[!NOTE]
Resource Context: This module provides expert patterns for Wave Loops. Accessed via Godot Master.
Architectural Thinking: The "Wave-State" Pattern
A Master implementation treats waves as Data-Driven Transitions. Instead of hardcoding spawn counts, use a WaveResource to define "Encounters" that the WaveManager processes sequentially.
Core Responsibilities
- Manager: Orchestrates the timeline. Handles delays between waves and tracks "Victory" conditions (all enemies dead).
- Spawner: Decoupled nodes that provide spatial context for where enemies appear.
- Resource: Immutable data containers that allow designers to rebalance the game without touching code.
Expert Code Patterns
1. The Async Wave Trigger
Use await and timers to handle pacing without cluttering the _process loop.
# wave_manager.gd snippet
func start_next_wave():
# Delay for juice/prep
await get_tree().create_timer(pre_delay).timeout
wave_started.emit()
_spawn_logic()2. Composition-Based Spawning
Manage enemy variety using a Dictionary-based composition strategy in your WaveResource.
# wave_resource.gd
@export var compositions: Dictionary = {
"Res://Enemies/Goblin.tscn": 10,
"Res://Enemies/Orc.tscn": 2
}Master Decision Matrix: Progression
| Pattern | Best For | Logic |
|---|---|---|
| Linear | Story missions | Hand-crafted list of WaveResource. |
| Endless | Survival modes | Code-generated WaveResource with multiplier math. |
| Triggered | RPG Encounters | Wave starts only when player enters an Area3D. |
NEVER Do
- NEVER iterate through get_children() to find all enemies — This is extremely slow. Always add enemies to an "enemies" group and use
get_tree().get_nodes_in_group(&"enemies")for efficient access. - NEVER constantly instantiate() and queue_free() hundreds of enemies — This causes garbage collection stutters. Use an object pool to reuse existing enemy instances.
- NEVER spawn thousands of separate MeshInstance3D nodes for swarms — This will tank your draw calls. Use
MultiMeshInstance3Dto batch thousands of meshes into a single GPU call. - NEVER calculate pathfinding for hundreds of agents on the main thread — This will freeze your game. Enable
use_async_iterationson your navigation regions or useNavigationServer3D.query_path(). - NEVER forget to check is_inside_tree() before adding a child — If the spawner is queued for deletion, adding a child will crash. Always verify the spawner is still active in the tree.
- NEVER assign a preloaded resource (like stats.tres) directly to spawned mobs — They will all share the exact same health/stats. Always call
base_stats.duplicate_deep()to give each mob its own unique data. - NEVER use standard strings for high-frequency group calls — Always use
StringName(&"enemies", &"take_damage") for optimal hash performance and to avoid unnecessary string allocations. - NEVER spawn entities directly inside physics callbacks synchronously — Instantiating nodes during physics steps can corrupt the physics state. Always use
call_deferred(&"add_child", enemy). - NEVER leave CollisionShapes on dead enemies active — Corpses will block towers and navigation. Use
set_deferred("disabled", true)immediately upon death. - NEVER synchronize complex Object types via MultiplayerSynchronizer — It only supports primitive types. For complex data, sync a UID or ID and look up the data locally on the client.
- NEVER auto-start waves without player feedback — Always provide a UI countdown, a visual "Wave Incoming" effect, or a start button to maintain player agency.
- NEVER hardcode spawn positions at (0,0,0) — Use
Marker3Dnodes in the editor so you can visually adjust spawn points without digging into code. - NEVER check wave completion by counting children every frame — It's too expensive. Maintain a local counter or use a signal-based system to track active enemy counts.
- NEVER use the same navigation map for every entity type — If you have flying and walking enemies, use separate navigation maps to prevent pathing issues.
- NEVER scale collision shapes non-uniformly for spawners — This breaks the collision detection math. Adjust the shape resource properties instead.
---
Available Scripts
MANDATORY: Read the appropriate script before implementing the corresponding pattern.
wave_loop_patterns.gd
10 Expert patterns: MultiMesh swarms, async pathfinding, background preloading, and server-side physics mobs.
wave_manager.gd
Orchestrates the timeline, delays between waves, and tracks "Victory" conditions.
wave_resource.gd
Data containers for wave compositions and difficulty settings.
wave_weighted_spawner.gd
Spatial spawner using weighted random selection for enemy variety.
---
Expert Wave Patterns
1. Occlusion Culling for Swarms
To optimize performance with hundreds of enemies, enable Occlusion Culling.
- Setup: Add an
OccluderInstance3Dto your arena and bake it. - Result: Enemies completely hidden behind walls/pillars won't be processed by the GPU, significantly boosting FPS.
2. Wave UI Architecture
Decouple your wave data from the UI using a CanvasLayer and signals.
- Wave Counter: Display current/total waves.
- Health Bars: Use a
TextureProgressBaron aCanvasLayerfor bosses, orSprite3Dwith a viewport texture for individual enemy health bars.
Reference
- Master Skill: godot-master
# wave_loop_patterns.gd
extends Node
# 1. Background Scene Preloading
# EXPERT NOTE: Prevents frame-stutters when a massive wave or big boss is about to spawn.
func prepare_boss_wave(scene_path: String) -> void:
ResourceLoader.load_threaded_request(scene_path)
# 2. Defereed Spawning for Physics Safety
# EXPERT NOTE: Ensures physics engines aren't interrupted by mid-frame instantiations.
func spawn_enemy_deferred(scene: PackedScene, spawn_pos: Vector3) -> void:
var enemy := scene.instantiate() as Node3D
enemy.position = spawn_pos
# Safely adds the child at the end of the frame
call_deferred(&"add_child", enemy)
# 3. Mass Broadcasting to Enemy Groups
# EXPERT NOTE: Instantly commands all mobs on the map to switch behavior states using StringName.
func enrage_active_enemies() -> void:
get_tree().call_group(&"enemies", &"enter_enrage_mode")
# 4. Asynchronous Navigation Pathfinding
# EXPERT NOTE: Offloads pathfinding calculations to background threads to handle hundreds of agents.
func request_enemy_path(start: Vector3, end: Vector3, callback: Callable) -> void:
var params := NavigationPathQueryParameters3D.new()
params.start_position = start
params.target_position = end
# Assuming callback takes the result as an argument
NavigationServer3D.query_path(params, _on_path_result.bind(callback))
func _on_path_result(result: NavigationPathQueryResult3D, callback: Callable) -> void:
callback.call(result.path)
# 5. Bypassing Nodes for Swarms (Server-Side)
# EXPERT NOTE: Spawns physical bodies directly in the C++ physics server for extreme scale (10,000+ units).
func create_server_only_mob(xform: Transform3D) -> RID:
var body_rid := PhysicsServer3D.body_create()
PhysicsServer3D.body_set_mode(body_rid, PhysicsServer3D.BODY_MODE_KINEMATIC)
PhysicsServer3D.body_set_space(body_rid, get_world_3d().space)
PhysicsServer3D.body_set_state(body_rid, PhysicsServer3D.BODY_STATE_TRANSFORM, xform)
return body_rid
# 6. Deep Duplication of Resource Stats
# EXPERT NOTE: Ensures every spawned mob gets a unique copy of the base stats to prevent shared health pools.
@export var base_enemy_stats: Resource
func setup_individual_stats(enemy_node: Node) -> void:
if enemy_node.has_method(&"set_stats"):
enemy_node.set_stats(base_enemy_stats.duplicate_deep())
# 7. Optimized Enemy Counting
# EXPERT NOTE: Quickly queries the engine's group count without iterating.
func get_active_enemy_count() -> int:
return get_tree().get_node_count_in_group(&"enemies")
# 8. Fast MultiMeshInstance Transforms
# EXPERT NOTE: Manipulates thousands of mesh transforms in a single call for minion swarms.
func batch_update_swarm_visuals(multi_mesh: MultiMesh, index: int, xform: Transform3D) -> void:
multi_mesh.set_instance_transform(index, xform)
# 9. Proper Avoidance Masking
# EXPERT NOTE: Stops swarming enemies from walking inside each other using NavigationServer.
func setup_mob_avoidance(agent_rid: RID, layer: int) -> void:
NavigationServer3D.agent_set_avoidance_enabled(agent_rid, true)
NavigationServer3D.agent_set_avoidance_mask(agent_rid, layer)
# 10. Despawning with Screen Notifications
# EXPERT NOTE: Frees engine memory automatically when a wave pushes an enemy out of bounds.
func _on_visible_on_screen_notifier_3d_screen_exited() -> void:
# Optional logic: only despawn if far enough or certain conditions met
queue_free()
# wave_manager.gd
# [GDSKILLS] godot-game-loop-waves
# EXPORT_REFERENCE: wave_manager.gd
extends Node
signal wave_started(wave_index: int)
signal wave_cleared(wave_index: int)
signal all_waves_complete()
signal enemy_spawned(enemy: Node)
@export var wave_sequence: Array[WaveResource] = []
@export var auto_start: bool = false
var current_wave_index: int = -1
var active_enemies: Array[Node] = []
var is_spawning: bool = false
func _ready() -> void:
if auto_start:
start_next_wave()
func start_next_wave() -> void:
if current_wave_index + 1 >= wave_sequence.size():
all_waves_complete.emit()
return
current_wave_index += 1
var current_wave = wave_sequence[current_wave_index]
if current_wave.pre_wave_delay > 0:
await get_tree().create_timer(current_wave.pre_wave_delay).timeout
_trigger_wave(current_wave)
func _trigger_wave(wave: WaveResource) -> void:
is_spawning = true
wave_started.emit(current_wave_index)
var spawn_list = []
for scene in wave.compositions:
var count = wave.compositions[scene]
for i in range(count):
spawn_list.append(scene)
if wave.random_spawning:
spawn_list.shuffle()
for enemy_scene in spawn_list:
_spawn_enemy(enemy_scene)
await get_tree().create_timer(1.0 / wave.spawn_rate).timeout
is_spawning = false
func _spawn_enemy(scene: PackedScene) -> void:
var enemy = scene.instantiate()
add_child(enemy)
active_enemies.append(enemy)
enemy.tree_exited.connect(_on_enemy_removed.bind(enemy))
enemy_spawned.emit(enemy)
func _on_enemy_removed(enemy: Node) -> void:
active_enemies.erase(enemy)
if active_enemies.is_empty() and not is_spawning:
wave_cleared.emit(current_wave_index)
start_next_wave()
# wave_resource.gd
# [GDSKILLS] godot-game-loop-waves
# EXPORT_REFERENCE: wave_resource.gd
extends Resource
class_name WaveResource
@export_group("Wave Metadata")
## The name of the wave for UI or logging.
@export var wave_name: String = "New Wave"
## Time in seconds before this wave starts after the previous one cleared.
@export var pre_wave_delay: float = 3.0
@export_group("Spawn Configuration")
## Dictionary of enemy scenes and their counts.
## Key: PackedScene, Value: int
@export var compositions: Dictionary = {}
## The rate at which enemies spawn (enemies per second).
@export var spawn_rate: float = 1.0
## If true, enemies spawn at random points. If false, they rotate through spawners.
@export var random_spawning: bool = true
# wave_spawner.gd
# [GDSKILLS] godot-game-loop-waves
# EXPORT_REFERENCE: wave_spawner.gd
extends Marker3D
@export var spawn_radius: float = 0.0
func get_spawn_position() -> Vector3:
if spawn_radius <= 0.0:
return global_position
var offset = Vector3(
randf_range(-spawn_radius, spawn_radius),
0,
randf_range(-spawn_radius, spawn_radius)
)
return global_position + offset
class_name WaveWeightedSpawner
extends Marker3D
## Wave spawner with weighted random enemy selection.
## Ensures wave variety by controlling spawn probabilities.
@export var enemy_scenes: Array[PackedScene] = []
## Parallel array to enemy_scenes. Higher values = higher probability.
@export var spawn_weights: PackedFloat32Array = []
@export var spawn_radius: float = 2.0
var _rng := RandomNumberGenerator.new()
func _ready() -> void:
_rng.randomize()
## Spawns a randomly selected enemy based on weights.
func spawn_enemy() -> Node3D:
if enemy_scenes.is_empty() or spawn_weights.size() != enemy_scenes.size():
push_error("WaveWeightedSpawner: enemy_scenes and spawn_weights must match in size.")
return null
# Expert weighted selection using RNG.rand_weighted
var index = _rng.rand_weighted(spawn_weights)
var enemy = enemy_scenes[index].instantiate() as Node3D
add_child(enemy)
enemy.global_position = _get_random_pos()
return enemy
func _get_random_pos() -> Vector3:
var angle = randf() * TAU
var distance = randf() * spawn_radius
return global_position + Vector3(cos(angle) * distance, 0, sin(angle) * distance)