Walk animation keeps playing even after I stop holding the move key

Godot Version

4.2.2

Question

See my below code. I added my first punch animation which works quite well. but If I move my player the walk cycle keeps playing after I stop pressing the key. Anyone able to assist?

var direction = Input.get_axis(“walk_left”, “walk_right”)
if is_on_floor():
if direction == 0:
if Input.is_action_just_pressed(“attack”):
animated_sprite.play(‘punch’)
elif direction != 0:
if Input.is_action_pressed(“walk_left”) or Input.is_action_pressed(‘walk_right’):
animated_sprite.play(‘walk’)
else:
animated_sprite.play(‘idle’)

func _on_animated_sprite_2d_animation_finished() ->void:
if animated_sprite.animation == 'punch:
animated_sprite.play(‘idle’)

Note that you can use the code formatting feature with ```, so we can see where are the indentations. I am going to assume this formatting:

var direction = Input.get_axis(“walk_left”, “walk_right”)
if is_on_floor():
    if direction == 0:
        if Input.is_action_just_pressed(“attack”):
            animated_sprite.play(‘punch’)
    elif direction != 0:
        if Input.is_action_pressed(“walk_left”) or Input.is_action_pressed(‘walk_right’):
            animated_sprite.play(‘walk’)
        else:
            animated_sprite.play(‘idle’)

You are asking Godot to play idle when direction != 0, while in fact you would like the idle animation to be played when direction == 0.

Maybe try something like:

var direction = Input.get_axis(“walk_left”, “walk_right”)
if is_on_floor():
    if direction == 0:
        if animated_sprite.current_animation != "idle":
             animated_sprite.play(‘idle’)
        if Input.is_action_just_pressed(“attack”):
            animated_sprite.play(‘punch’)
    elif direction != 0:
        if animated_sprite.current_animation != "walk":
            animated_sprite.play(‘walk’)

Let us know how it goes!

Hi,

Thanks,

This worked great

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.