In the game, mobs will keep spawning forever and accumulate. This can cause performance problems and make the screen too crowded if the game runs for a long time. Here's how to limit the total number of mobs that can exist at the same time.
To implement this feature, you need to modify the
res://game.gd script. Here's the updated code broken down
step by step.
First, we add a variable to keep track of the current number of mobs and a
constant to define the maximum allowed (MAX_MOBS):
extends Node2D
+const MAX_MOBS = 50
+
+var mob_count = 0
Then, we update the spawn_mob() function to count mobs and check if we've
reached the maximum number of mobs before spawning a new one. When we create a
new mob, we also increase our mob_count variable.
func spawn_mob():
+ if mob_count >= MAX_MOBS:
+ return
%PathFollow2D.progress_ratio = randf()
var new_mob = preload("res://mob.tscn").instantiate()
new_mob.global_position = %PathFollow2D.global_position
add_child(new_mob)
+ mob_count += 1
Next, we need to detect when mobs leave the game. For that we connect to the
tree_exited signal for each mob we create. Every node emits this signal when
it gets removed from the scene tree, which happens when mobs get destroyed by
bullets.
func spawn_mob():
if mob_count >= MAX_MOBS:
return
%PathFollow2D.progress_ratio = randf()
var new_mob = preload("res://mob.tscn").instantiate()
new_mob.global_position = %PathFollow2D.global_position
add_child(new_mob)
mob_count += 1
+ new_mob.tree_exited.connect(_on_mob_tree_exited)
+func _on_mob_tree_exited():
+ mob_count -= 1
Here, we connect the new mob's tree_exited signal to our
_on_mob_tree_exited() function. This means whenever this mob gets destroyed,
Godot will call our function once.
The _on_mob_tree_exited() function decreases our counter by 1. This makes room
for a new mob to spawn next time the timer times out.
With these changes, the game will now limit the number of mobs to 50 at any
given time. You can adjust the MAX_MOBS constant to increase or decrease this
limit for your game.