How to play animation using body_entered function?

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

I have a fireball that should switch to a new explode animation upon contact with a physics body. Is there a way to play an animation using the body_entered function?

I would have figured with the below code the fireball would just pass through objects and play the new animation?

I’ve tested queue_free and the fireball correctly interacts with bodies and gets removed from memory, but I can’t get the animation to change.

func _on_Fireball_body_entered(body):
	$AnimatedSprite.play("explo")
	# queue_free()
:bust_in_silhouette: Reply From: omggomb

If you call queue_free() right after you start your new animation, the animation won’t show because your fireball will be removed pretty much instantly. Keep in mind that while queue_free() does not immediately delete an object, it will be deleted in the next frame, so at 60 fps it will be gone in about 16.6 milliseconds.

You could do something like

func _on_Fireball_body_entered(body):
    $AnimatedSprite.play("explo")
    yield($AnimatedSprite, "animation_finished")
    queue_free()

This will pause the body entered function until the animation has finished (signal animation_finished is emitted by AnimatedSprite and then free the fireball (the code above is untested, but you get the idea :slight_smile: ).

For more info on yield, see the docs.

:bust_in_silhouette: Reply From: Gat5lol

podrías probar con esto

func _on_Fireball_body_entered(body): 
    if body == player:
	$AnimatedSprite.playing = true
	$Timer.start()
func _on_timer_timeout():
    queue_free()

ajustando en tiempo según cuando acabe la animación