Want enemy to play "hurt" animation when hit

I’m pretty new to Godot, it has only been 2 days. Take it easy on me guys😁

Godot 4.2

I want my animation to play when my enemy gets hit. I created a “hurt” animation in my animatedsprite2d and called it in my script under the player hurt function to play the animation, however it does not play and it continues with the idle animation.
Here is the script:

extends CharacterBody2D

var speed = 40
var player_chase = false
var player = null
var player_inattack_zone = false

var health = 100
var can_take_damage = true

##########where it all began with the healthbar##############
@onready var healthbar = $Healthbar

func _ready():

func _physics_process(delta):
	if player_chase: #or you can also say if player_chase == true:
		position += (player.position - position)/speed
		if(player.position.x - position.x) < 0:
			$AnimatedSprite2D.flip_h = true
			$AnimatedSprite2D.flip_h = false

func _on_detection_area_body_entered(body):
	player = body
	player_chase = true

func _on_detection_area_body_exited(body):
	player = null
	player_chase = false

func enemy():

func _on_enemy_hitbox_body_entered(body):
	if body.has_method("player"):
		player_inattack_zone = true

func _on_enemy_hitbox_body_exited(body):
	if body.has_method("player"):
		player_inattack_zone = false

func deal_with_damage():
	if can_take_damage == true:
		if player_inattack_zone and global.player_current_attack == true:
			health = health - 20
			can_take_damage = false
			print("slime health =", health)
			if health <= 0:

func _on_take_damage_cooldown_timeout():
	can_take_damage = true

func update_health():
	healthbar.health = health

func _on_hurt_anim_timer_timeout():

You’re resetting the (correct) animation track that you’ve set in deal_with_damage() immediately with the last portion of your _physics_process which will either play the “walk” animation (if player_chase is true) or the “idle” animation otherwise.

Sorry that kinda went over my head a little bit. So in this case what must i do?

Prevent the execution of that last part until your hurt animation has finished. There are many ways to achieve this, but in your case, the easiest would probably be to check AnimatedSprite2D.is_playing() while the hurt animation is active (assuming you disabled “Animation Looping” for it):

func _physics_process(delta):

    if $AnimatedSprite2D.animation == "hurt" and $AnimatedSprite2D.is_playing():
        return # early

    if player_chase:
        # ...
1 Like

Thank you soo much!! It works! You are the GOAT! God bless you!

1 Like