How to loop through animation while holding keyboard key?

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

I’m trying to run animation of walking on my player, if i press right arrow the animations plays but i want it to loop as long as i hold the key.

Does anyone know how to do this?

This is some of the code:

...
    func _process(delta):
    
        velocity.y += delta * GRAVITY
        if (Input.is_action_pressed("ui_left")):
            velocity.x = - WALK_SPEED
            anim.play("walk")
    
        elif (Input.is_action_pressed("ui_right")):
            velocity.x = WALK_SPEED
            anim.play("walk")
    
        else:
            velocity.x = 0
    
    ....
    
    func _ready():
    	anim = get_node("AnimationPlayer")
    	set_process(true)
:bust_in_silhouette: Reply From: rredesigns

Is the animation looped in the animation player?

There’s a button to make it loop, walking animations should be looped. Maybe it would still work if you use while instead of if.

I made a character walk by just playing from idle to walking at keypress, then from walking back to idle.

yes the animation is looped in the player.

The problem here is, I think, that function _process() is called every frame.
So because of that the animation always starts from the beginning, do you
know if there is the way to delay the play of animation until it hits the last
key frame?

mythaone | 2016-07-26 21:56

:bust_in_silhouette: Reply From: jospic

maybe you should use _input() instead of _process()

regards
-j

Thank you so much my man. That was it :slight_smile:

Rocket_man | 2017-08-05 15:11

:bust_in_silhouette: Reply From: Akien

The problem here is that you restart the animation at each frame, so you don’t let it run fully, and it likely appears like it’s not working until you stop pressing the button.

You should keep track of the currently playing animation, and only run anim.play() when the animation should change.

Check the platformer 2D demo, DynaDungeons, Minilens (simple ones) or Jetpaca (more complex, search for the new_anim string).

Great, tnx :slight_smile:

mythaone | 2016-07-27 11:29