So, I'm making this 2d game where player moves forward only in one direction (no going back). the camera also moves with the player. Now, I want the enemy instances to get removed from the scene once they are out of sight (left the screen). Any suggestion will be welcome.
How do I remove the "enemy" instances after they leave the camera?
Comment was stuck in moderation queue. Might want to check your email(spam folder included) to make sure you didn't miss the confirmation email.
You can check the x position of the enemy and if it's less than a certain number (off screen) call queue_free() to remove it. Usually this is fine to put on the enemy object itself, so if you have multiple enemies they will all be removed individually.
Also, depending on how your world/camera moves, you may have to do some math to figure out what the "off screen" x value is. If the camera itself is moving, then you want to take the difference of the enemy position and the camera position, if that number is larger than half the screen width (plus a little bit so the enemies don't disappear early) then you can remove the enemy (with queue_free() as mentioned before).
Hope that makes sense.
- Edited
What I used to use in one of my game projects is the VisibilityNotifier2D
node. It emits a signal whenever its bounding rectangle leaves the screen, screen_exited
. Just pop one of these in your enemys' scene, adjust it's rectangle, and connect the signal to the enemy script. Then inside said script, you'd have something like this.
func _on_VisibilityNotifier2D_screen_exited():
# Do some stuff to get ready for deletion.
queue_free()