gae_wild_jam/scripts/enemy_base.gd

109 lines
2.9 KiB
GDScript

class_name EnemyBase
extends CharacterBody2D
@onready var animated_sprite_2d: AnimatedSprite2D = $AnimatedSprite2D
@export var drop_table: Array[DropTable]
@export var damage: int = 2
@export var max_hp: int = 10
var is_dying = false
var is_hurt = false
var hp: int
var _touching_witch: bool = false
var speed
var witch
var player
var death_sound = preload("res://assets/music&sfx/sfx/hit2.wav")
var last_direction := Vector2.DOWN
signal died
var xp = 1
func _ready() -> void:
add_to_group("enemies")
died.connect(get_node("/root/Game/DropManager").on_enemy_died)
witch = get_node("/root/Game/Witch")
player = get_node("/root/Game/Player")
animated_sprite_2d.sprite_frames = animated_sprite_2d.sprite_frames.duplicate()
hp = max_hp
$Area2D.body_entered.connect(_on_base_body_entered)
$Area2D.body_exited.connect(_on_base_body_exited)
func _on_base_body_entered(body: Node2D) -> void:
if body == witch:
_touching_witch = true
func _on_base_body_exited(body: Node2D) -> void:
if body == witch:
_touching_witch = false
func die():
is_dying = true
collision_layer = 0
var death_anim: String
if abs(last_direction.x) >= abs(last_direction.y):
death_anim = "death_left" if last_direction.x < 0 else "death_right"
else:
death_anim = "death_up" if last_direction.y < 0 else "death_down"
animated_sprite_2d.sprite_frames.set_animation_loop(death_anim, false)
animated_sprite_2d.play(death_anim)
var player = AudioStreamPlayer.new()
add_child(player)
player.stream = death_sound
player.bus = "SFX"
player.play()
died.emit(self)
await animated_sprite_2d.animation_finished
queue_free()
func take_damage(amount: int) -> void:
if is_dying or is_hurt:
return
hp -= amount
if hp <= 0:
die()
else:
_play_hurt()
func hit() -> void:
take_damage(1)
func _play_hurt() -> void:
var hurt_anim: String
if abs(last_direction.x) >= abs(last_direction.y):
hurt_anim = "hurt_left" if last_direction.x < 0 else "hurt_right"
else:
hurt_anim = "hurt_up" if last_direction.y < 0 else "hurt_down"
if not animated_sprite_2d.sprite_frames.has_animation(hurt_anim):
return
is_hurt = true
animated_sprite_2d.sprite_frames.set_animation_loop(hurt_anim, false)
animated_sprite_2d.play(hurt_anim)
await get_tree().create_timer(0.25, true).timeout
is_hurt = false
func _process(delta: float) -> void:
if _touching_witch and not is_dying:
witch.take_damage(damage)
func _chase_witch() -> void:
var direction = Vector2(witch.global_position - global_position).normalized()
if direction != Vector2.ZERO:
last_direction = direction
velocity = direction * speed
if direction == Vector2.ZERO:
animated_sprite_2d.play("idle")
elif abs(direction.x) >= abs(direction.y):
if direction.x < 0:
animated_sprite_2d.play("walk_left")
else:
animated_sprite_2d.play("walk_right")
else:
if direction.y < 0:
animated_sprite_2d.play("walk_up")
else:
animated_sprite_2d.play("walk_down")
move_and_slide()