Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | Pyhrrous |
Hi, I’m working on a game where if an enemy goes offscreen or dies, if the player revisits the position they originally started from then they respawn at that position. However, how I have the code currently set up doesn’t work how I expect:
# for setting things when this comes onscreen
func _on_VisibilityNotifier2D_screen_entered():
if (can_spawn):
visible = true;
set_physics_process(true)
health = MAX_HEALTH
motion = Vector2()
can_spawn = false
#disable things when they leave the screen + reset them to
#their starting position
func _on_VisibilityNotifier2D_screen_exited():
set_physics_process(false)
set_position(starting_position)
print($VisibilityNotifier2D.is_on_screen())
#only allow this to spawn if the spawn position is not onscreen
if (!$VisibilityNotifier2D.is_on_screen()):
can_spawn = true;
visible = false;
What is supposed to happen is that when an object goes offscreen, it teleports back to the position back to where it started off. If the starting position is still onscreen however, then the object will need to be scrolled offscreen again before it can be spawned – thus, the if(!is_on_screen()): can_spawn = true
check. Here’s a finite state machine diagram for the intended behaviour in case it’s unclear:
What actually happens though is that the object instantly spawns regardless of the aforementioned check. Looking at some print() debugging, is_on_screen() always returns false from this method, even if the object was just moved onscreen.
Can anyone recommend any ways to fix this? I was thinking of using a 1-frame timer to make sure the object cannot respawn in the same frame that it despawns, but I was wondering if there were any better solutions.