68 lines
1.8 KiB
GDScript
68 lines
1.8 KiB
GDScript
class_name Enemy extends CharacterBody2D
|
|
|
|
const DIR_4 = [
|
|
Vector2.RIGHT,
|
|
Vector2.DOWN,
|
|
Vector2.LEFT,
|
|
Vector2.UP,
|
|
]
|
|
|
|
signal direction_changed(new_direction: Vector2)
|
|
signal enemy_damaged(hurtbox: Hurtbox)
|
|
signal enemy_destroyed(hurtbox: Hurtbox)
|
|
|
|
@export var hp: int = 3
|
|
|
|
@onready var animation_player: AnimationPlayer = $AnimationPlayer
|
|
@onready var main_sprite: Sprite2D = $main_sprite
|
|
@onready var hitbox: Hitbox = $Hitbox
|
|
@onready var state_machine: EnemyStateMachine = $enemy_state_machine
|
|
|
|
var cardinal_direction : Vector2 = Vector2.DOWN
|
|
var direction : Vector2 = Vector2.ZERO
|
|
var invulnerable: bool = false
|
|
|
|
func _ready() -> void:
|
|
state_machine.initialize(self)
|
|
hitbox.damaged.connect(on_damage)
|
|
|
|
func _process(_delta: float) -> void:
|
|
pass
|
|
|
|
func _physics_process(_delta: float) -> void:
|
|
move_and_slide()
|
|
|
|
func set_direction(new_direction: Vector2) -> bool:
|
|
if new_direction == Vector2.ZERO:
|
|
return false
|
|
|
|
var refreshed_direction = DIR_4[int(round((new_direction + cardinal_direction * 0.1).angle() / TAU * DIR_4.size()))]
|
|
|
|
if refreshed_direction == cardinal_direction:
|
|
return false
|
|
cardinal_direction = refreshed_direction
|
|
direction_changed.emit(refreshed_direction)
|
|
main_sprite.scale.x = -1 if cardinal_direction == Vector2.LEFT else 1
|
|
return true
|
|
|
|
func update_animation(state: String) -> void:
|
|
animation_player.play(state + "_" + get_animation_direction())
|
|
|
|
func get_animation_direction() -> String:
|
|
var newAnimDirection: String = "side"
|
|
if cardinal_direction == Vector2.DOWN:
|
|
newAnimDirection = "down"
|
|
elif cardinal_direction == Vector2.UP:
|
|
newAnimDirection = "up"
|
|
return newAnimDirection
|
|
|
|
func on_damage(hurtbox: Hurtbox) -> void:
|
|
if invulnerable:
|
|
return
|
|
hp -= hurtbox.damage
|
|
if hp > 0:
|
|
enemy_damaged.emit(hurtbox)
|
|
else:
|
|
enemy_destroyed.emit(hurtbox)
|
|
|