player attack isn't working

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

so I’m trying to make the player attack but it isn’t working somehow and I don’t know why
here is my player code:

extends KinematicBody2D

var velocity : Vector2

export var max_speed : int = 600
export var gravity : float = 35
export var jump_force : int = 1600
export var acceleration : int = 50
export var jump_buffer_time : int  = 15
export var cayote_time : int = 15

var jump_counter : int = 0
var jump_buffer_counter : int = 0
var cayote_counter : int = 0

func _physics_process(_delta):

if is_on_floor():
	cayote_counter = cayote_time
	jump_counter = 0

if not is_on_floor():
	if cayote_counter > 0:
		cayote_counter -= 1
	
if jump_buffer_counter > 0 and jump_counter < 1:
	jump_counter += 1
	cayote_counter = 1

velocity.y += gravity
if velocity.y > 2000:
	velocity.y = 2000

if Input.is_action_pressed("right"):
	velocity.x += acceleration 
	$Sprite.flip_h = false
	get_node("AnimationPlayer").play("run")
elif Input.is_action_pressed("left"):
	velocity.x -= acceleration
	$Sprite.flip_h = true
	get_node("AnimationPlayer").play("run")
elif Input.is_action_pressed("jump"):
	get_node("AnimationPlayer").play("jump")
elif Input.is_action_just_released("attack"):
		attack()
else:
	velocity.x = lerp(velocity.x,0,0.2)
	get_node("AnimationPlayer").play("idle")

velocity.x = clamp(velocity.x, -max_speed, max_speed)

if Input.is_action_just_pressed("jump"):
	jump_buffer_counter = jump_buffer_time
	get_node("AnimationPlayer").play("jump")

if jump_buffer_counter > 0:
	jump_buffer_counter -= 1

if jump_buffer_counter > 0 and cayote_counter > 0:
	velocity.y = -jump_force
	jump_buffer_counter = 0
	cayote_counter = 0

if Input.is_action_just_released("jump"):
	if velocity.y < 0:
		velocity.y += 400

velocity = move_and_slide(velocity, Vector2.UP)


func attack_detected():
print("hit")



func attack():
get_node("AnimationPlayer").play("Attack")
print("attack")

is_action_just_released seems like a weird choice for an attack. Perhaps consider changing it to is_action_just_pressed?

spaceyjase | 2023-06-15 15:37

yes it’s now working but the animation isn’t appearing

Mhd08 | 2023-06-16 13:48

:bust_in_silhouette: Reply From: Zylann

Is attack printed? No typo in the animation name?

_physics_process is called almost every frame.
Perhaps your code plays another animation immediately the next physics frame, which overrides it.
Your code does this when no input is pressed during the current physics frame:

get_node("AnimationPlayer").play("idle")`

Which will probably be the case in every physics frame following the frame in which the attack button was released.

So you may want to avoid playing idle until the attack animation has finished.