Wait for animation to finish

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By edimemune
:warning: Old Version Published before Godot 3 was released.

I am working on a game with a ball that moves and avoids the obstacles, something like Mario. I need to play an animation while a button is pressed and play idle while it’s not pressed.
Here is the code:

extends RigidBody2D

var anim

func _ready():
	anim = get_node("AnimatedSprite")
	anim.play("idle")
	set_fixed_process(true)

func _fixed_process(delta):
	if(Input.is_key_pressed(KEY_SPACE)):
		anim.play("jump")
	
	if(Input.is_key_pressed(KEY_LEFT)):
		anim.play("walk")

How can I achieve this?

:bust_in_silhouette: Reply From: cardoso

I think what might be happening is that when you press a button the animation line is triggered several times, for every _fixed_process “cicle”, and not only once, and the animation is reset.

So a quick way to fix that would be to have a bolean variable:

var is_ani_started = false

func _fixed_process(delta):
    if(Input.is_key_pressed(KEY_SPACE) and !is_ani_started ):
        anim.play("jump")
        is_ani_started = true

    if(Input.is_key_pressed(KEY_LEFT)  and !is_ani_started ):
        anim.play("walk")
        is_ani_started = true

But you also need to know when the animation ended, in case you just are not pressing any button at all anymore.

So you can use the AnimationPlayer ended (or finished?) signal, connecting it to a function like this:

func _onAnimationEnded():
      is_ani_started = false

This was something I remember doing long time ago, but I then switched to states (FSM - Finite State Machine), which give better control and more organized code.
(You can find great video tutorial on those here:
https://www.youtube.com/watch?v=y2HBgjNxS4s)