0 votes

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?

in Engine by (61 points)
edited by

1 Answer

0 votes
Best answer

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)

by (384 points)
selected by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.