$AnimationPlayer2D only playing the first frame of animations after an attack animation.

Godot Version 4

Question:

$AnimationPlayer2D is only playing the first frame of other animations after doing an attack animation. This didn’t happened before adding func_on_animated_sprite_2d_animation_finished(): and func player_attack():. I would be very glad if anyone could help me, here are my codes and thank you for anyone trying to help.

extends CharacterBody2D

@export var movement_speed : float = 300
var character_direction : Vector2
var attacking = false

func player_control():
	#attack check
	if attacking == false:
	
	#movement
		character_direction.x = Input.get_axis("move_left", "move_right")
		character_direction.y = Input.get_axis("move_up", "move_down")
		character_direction = character_direction.normalized()
	
	#flip
		if character_direction.x > 0:
			$AnimatedSprite2D.flip_h = false
		elif character_direction.x < 0:
			$AnimatedSprite2D.flip_h = true
	 
	#animations
		if character_direction:
			velocity = character_direction * movement_speed
			if $AnimatedSprite2D.animation != "walking":
				$AnimatedSprite2D.animation = "walking"
		else:
			velocity = velocity.move_toward(Vector2.ZERO, movement_speed)
			if $AnimatedSprite2D.animation != "idle":
				$AnimatedSprite2D.animation = "idle"

func player_attack():
	if Input.is_action_just_pressed("attack"):
		$AnimatedSprite2D.play("attack_one")
		velocity.x = 0
		velocity.y = 0
		attacking = true

func _physics_process(delta):
	player_control()
	player_attack()
	move_and_slide()


func _on_animated_sprite_2d_animation_finished():
	if $AnimatedSprite2D.animation == "attack_one":
		attacking = false

I don’ see where you are using this function, to be honest. Also, have you considered using a very simple state machine to manage your character states?

Personally I would consider this check not very optimal as it makes code readability a bit harder (imagine if you add more complexity, code readability will decrease more than linearly imo). If you want to keep this approach, perhaps consider inverting the check to return if true, so you avoid having to indent the whole method under an if statement.

Also, unless attacking is strictly physics related I would avoid calling that in the physics process, rather in the process one. As the name implies, physics process is… well… for physics ahah :slight_smile:

Hey, thank you for the tips! I have managed to add a state machine to the player and everything is working fine right now. Have a nice day!

1 Like