Godot Version
Godot 4.3
Question
Hello, i’m kind of a beginner in coding so i need help.
My Hit animation when enemy is getting hit and death animation is not working.
Why?
Idle and Running works fine and area detection also.
Enemy script:
extends CharacterBody2D
class_name Schroom
var speed = 0.5
var health_max = 100
var health_min = 0
var dead : bool = false
var player_chase : bool = false
var player : CharacterBody2D
var direction : Vector2
var is_taking_damage : bool = false
var damage_to_deal = 10
var is_dealing_damage : bool = false
const gravity = 900
var knockback_force = -100
@onready var animated_sprite_2d: AnimatedSprite2D = $AnimatedSprite2D
@export var health : float = 100
func _physics_process(delta: float) → void:
if !is_on_floor():
velocity.y += gravity * delta
velocity.x = 0
move(delta)
handle_animation()
move_and_slide()
func move(delta):
var player = Global.playerBody
if !dead:
if player_chase and !is_taking_damage:
velocity = position.direction_to(player.global_position) * speed
velocity.y += gravity * delta
position.x += velocity.x
direction.x = abs(velocity.x) / velocity.x
elif is_taking_damage:
var knockback_dir = position.direction_to(player.position) * knockback_force
velocity.x = knockback_dir.x
print(“taking damage”)
move_and_slide()
func handle_animation():
if player_chase and !is_taking_damage:
animated_sprite_2d.play(“Run”)
if direction.x < 0:
animated_sprite_2d.flip_h = false
elif direction.x > 0:
animated_sprite_2d.flip_h = true
else:animated_sprite_2d.play(“Idle”)
if !dead and is_taking_damage and !is_dealing_damage:
animated_sprite_2d.play(“Hit”)
await get_tree().create_timer(0.33).timeout
is_taking_damage = false
if !dead and !is_taking_damage and is_dealing_damage:
animated_sprite_2d.play(“Attack”)
elif dead:
animated_sprite_2d.play(“Death”)
await get_tree().create_timer(1.0).timeout
handle_death()
func handle_death():
queue_free()
func _on_animated_sprite_2d_animation_finished() → void:
if animated_sprite_2d.animation == “Death”:
queue_free()
func _on_detection_area_body_entered(body: Node2D) → void:
player = body
player_chase = true
print(“player entered”)
func _on_detection_area_body_exited(_body: Node2D) → void:
player = null
player_chase = false
is_on_floor()
velocity.x = 0
print(“player exited”)
func _on_hitbox_area_entered(area: Area2D) → void:
var damage = Global.sword_damage
if area == Global.attack_area:
take_damage(damage)
print(“taken damage”, damage)
func take_damage(damage):
health -= damage
is_taking_damage = true
if health <= health_min:
health = health_min
die()
print(str(self), “health”, health)
func die():
dead = true
animated_sprite_2d.play(“Death”)