[Beginner] Removing spawned mobs based on player position

Godot Version

Godot 4.4.1 Mac OS

Question

`

The challenge is to delete spawned mobs once the distance is bigger then 1500px from player .

Function for spawning

func spawn_mob():
var new_mob = preload(“res://enemy.tscn”).instantiate()
%PathFollow2D.progress_ratio = randf()
new_mob.global_position = %PathFollow2D.global_position
add_child(new_mob)

What method be most effective for removal ? I thought use rectangle shape twice of size camera view field from pivot to remove any child with position outside .

Thank you for any suggestions, tips , codes

`

You could just put this in the mob script:

const MAX_RANGE: float = 1500 ** 2

func _process(delta: float) -> void:
    #[...]
    if global_position.distance_squared_to(player.global_position) > MAX_RANGE:
        queue_free()

You’ll need a reference to the player for that, but you’ll probably need that in the mob anyways.

1 Like

a rectangle shape would be fine, but if you want a more even deletion, I sugest a circle (or sphere if ur doing 3d) and have a setup where a circle colision shape 2d is the child of an area 2d. you could have it so if the monstor isn’t detecting that area by using something like

func remove_self(area):
   for areas in area:
      var detected_safezone = false
      if area.name != "SafetyZone":
         pass
      else:
         detected_safezone = true
         break
      if detected_safezone != true:
         queue_free()
1 Like

I’d use an Area2D on the enemy, and give it a CollisionShape2D with a circle the radius of 1500. Set the Area2D’s layers to nothing and mask to the player’s physics mask. Then just attach the body_exited signal and add some code:

func _on_body_exited(body: Node2D) -> void:
    queue_free()

The benefit of this is less math, and if you want to change the shape or the size of the detection it’s really easy to do. As long as the player is the only thing ever on that physics layer, nothing else will delete the enemy.

1 Like