Delete an object when he reach a position

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Matteo

Hi guys,
I’m doing a platform and I want to delete the bullet that my player shoot only when is like 400 pixel from the spawn position; how can i do this? Thank you in advance

:bust_in_silhouette: Reply From: jgodfrey

The specifics will depend on how you’ve scripted the objects in question. From a high-level, you’ll need:

  • A way to calculate the distance between 2 Vector2 objects (the spawn point and the current point). For this you can use the distance_to function of Vector2. The distance from the spawn point to the current point is just:
bulletSpawnPosition.distance_to(bullet.position)
  • A way to delete the bullet once it’s reached our maximum distance. For that, you need to queue_free() the bullet.

So, as a rough example:

func _process(delta):
    if bulletSpawnPosition.distance_to(bullet.position) > 400:
        bullet.queue_free()

Just season to taste…