why does the animation doesn't play

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By swordsman

im very new to godot and its programing is hard for me im trying to make a 2d platformer game but the melee animation wont work when i press the attack button the melee animation just does the first frame and then goes to the idle or run animation please help me i dont understand it

here is my player script:

extends KinematicBody2D

const UP = Vector2(0,-1)
const gravity = 20
const max_fall_speed = 200 
const max_speed = 100
const jump_force = 350
const accel = 10

var motion = Vector2()
var facing_right = true
var attacking = false

func _ready():
	pass

func _physics_process(delta):
	
	motion.y += gravity
	if motion.y > max_fall_speed:
		motion.y = max_fall_speed
	
	if facing_right == true:
		$player_sprite.scale.x = 1
	else:
		$player_sprite.scale.x = -1
	
	motion.x = clamp(motion.x, -max_speed, max_speed)
	
	if Input.is_action_pressed("right"):
		motion.x += accel
		facing_right = true
		$AnimationPlayer.play("run")
	elif Input.is_action_pressed("left"):
		motion.x -= accel
		facing_right = false
		$AnimationPlayer.play("run")
	else:
		motion.x = lerp(motion.x, 0, 0.2)
		$AnimationPlayer.play("idle")
	
	if Input.is_action_just_pressed("attack"):
		attacking = true
	else:
		attacking = false
	
	if is_on_floor():
		if Input.is_action_just_pressed("jump"):
			motion.y = -jump_force
	
	if Input.is_action_just_released("jump") && motion.y < 0:
		motion.y = 0
	
	if !is_on_floor():
		if motion.y < 0:
			$AnimationPlayer.play("jump")
		elif motion.y > 0:
			$AnimationPlayer.play("fall")
	
	motion = move_and_slide(motion,UP)


func _process(delta):
	if attacking == true:
		$AnimationPlayer.play("attack_1")

func _on_sword_hit_area_entered(area):
	if area.is_in_group("hurtbox"):
		area.take_damage()
:bust_in_silhouette: Reply From: avencherus

play() will restart the animation, and the logic is going to do this every frame. You need to check if the animation is currently playing before calling play() again, otherwise it will keep jumping to time 0.

For example:

if Input.is_action_pressed("right"):
    motion.x += accel
    facing_right = true
    
    if($AnimationPlayer.current_animation != "run"):
	        $AnimationPlayer.play("run")