
Я создал через Area2D коллизию, на которую будет реагировать урон. Но почему-то не работает.
код Героя
extends CharacterBody2D
const SPEED = 300.0
const JUMP_VELOCITY = -400.0
var attacking = false
@onready var anim = $AnimatedSprite2D
@onready var attack_area = $AttackArea
func _physics_process(delta: float) -> void:
# Add the gravity.
if not is_on_floor():
velocity += get_gravity() * delta
if Input.is_action_just_pressed("attack") and not attacking:
start_attack()
# Поки триває атака — не виконуємо інші дії
if attacking:
move_and_slide()
return
if Input.is_action_just_pressed("ui_accept") and is_on_floor():
velocity.y = JUMP_VELOCITY
anim.play("Jump")
var direction := Input.get_axis("ui_left", "ui_right")
if direction:
velocity.x = direction * SPEED
if velocity.y == 0:
anim.play("Run")
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
if velocity.y == 0:
anim.play("Idle ")
if direction == -1:
$AnimatedSprite2D.flip_h = true
elif direction == 1:
$AnimatedSprite2D.flip_h = false
if velocity.y >0:
anim.play("Fall")
move_and_slide()
velocity.x = 0
func _on_animated_sprite_2d_animation_finished() -> void:
if anim.animation == "Attack":
attacking = false
func start_attack():
attacking = true
anim.play("Attack")
attack_area.monitoring = true
await anim.animation_finished
attack_area.monitoring = false
attacking = false
func _on_attack_area_body_entered(body: Node2D):
if body.is_in_group("enemies") and body.has_method("take_damage"):
body.take_damage(100)
# Додатковий ефект відштовхування
var knockback_direction = (body.global_position - global_position).normalized()
body.velocity = knockback_direction * 200
и код моба
extends CharacterBody2D
var max_health = 100
var current_health = max_health
var is_alive = true
var chase = false
var speed = 50
@onready var anim = $AnimatedSprite2D
func _ready():
add_to_group("enemies")
func take_damage(damage):
if !is_alive: return
current_health -= damage
if current_health <= 0:
die()
func die():
is_alive = false
anim.play("Death")
await anim.animation_finished # Чекаємо завершення анімації
queue_free()
func _physics_process(delta: float) -> void:
if not is_on_floor():
velocity += get_gravity() * delta
var player = $"../../Hero/Hero"
var direction = (player.position - self.position).normalized()
if chase == true:
velocity.x = direction.x * speed
anim.play("Run")
else:
velocity.x = 0
anim.play("Idle")
if direction.x < 0:
$AnimatedSprite2D.flip_h = true
else:
$AnimatedSprite2D.flip_h = false
move_and_slide()
func _on_detector_body_entered(body: Node2D) -> void:
if body.name == "Hero":
chase = true
func _on_detector_body_exited(body: Node2D) -> void:
if body.name == "Hero" :
chase = false