Animations breaking after playing attack animation

Godot Version

4.2.2

Question

this is the code for the player

extends CharacterBody2D

const SPEED = 10000.0

@onready var sprite = $AnimatedSprite2D

var direction = "forward"

func _physics_process(delta):
	var direction_x = Input.get_axis("left", "right")
	if direction_x:
		velocity.x = direction_x * SPEED * delta
		if(direction_x > 0):
			direction = "right"
		else:
			direction = "left"
	else:
		velocity.x = move_toward(velocity.normalized().x, 0, SPEED)
		
	var direction_y = Input.get_axis("up", "down")
	if direction_y:
		velocity.y = direction_y * SPEED * delta
		if(direction_y > 0):
			direction = "forward"
		else:
			direction = "backward"
	else:
		velocity.y = move_toward(velocity.normalized().y, 0, SPEED)
		
	move_and_slide()
	animations()

func _input(event):
	if(event.is_action_pressed("attack")):
		sprite.animation = "attack_" + direction

func animations():
	if(!str(sprite.animation).begins_with("attack")):
		if velocity != Vector2.ZERO:
			sprite.animation = "run_" + direction
		else:
			sprite.animation = "idle_" + direction

func _on_animated_sprite_2d_animation_finished():
	if(str(sprite.animation).begins_with("attack")):
		sprite.animation = "idle_" + direction

after attacking, all the animations get stuck at the second frame

One problem I see is that you aren’t guarding against other input events when it comes to attacking. Let’s say you press and hold attack.

Every time you move a direction, those key events go through _input and since you are holding attack key it will set attack again.

Use event.is_action("attack") and event.pressed

There could also be some order of operations with using the process function and _input together to handle player movement…

I would also suggest using an animation tree. They have the capability to read state changes on the player and you can setup animation transitions outside of the code. You just need to maintain the a state the player is in.