2024-10-01 16:43:34 +02:00
|
|
|
extends StaticBody2D
|
|
|
|
|
|
2024-10-23 14:57:06 +02:00
|
|
|
@export var max_health: float = 100.0
|
2024-10-01 16:43:34 +02:00
|
|
|
var current_health: float
|
2024-10-23 14:57:06 +02:00
|
|
|
var is_destroyed: bool = false
|
|
|
|
|
var event_bus: EventBus
|
2024-10-01 16:43:34 +02:00
|
|
|
|
|
|
|
|
func _ready():
|
|
|
|
|
current_health = max_health
|
2024-10-23 14:57:06 +02:00
|
|
|
event_bus = get_node("/root/Main/MainEventBus")
|
|
|
|
|
event_bus.subscribe_to(get_node("/root/Main/DamageEventScope"), "DamageEvent", Callable(self, "on_damage_event"))
|
|
|
|
|
add_to_group("asteroids")
|
|
|
|
|
update_health_label()
|
2024-10-01 16:43:34 +02:00
|
|
|
|
2024-10-23 14:57:06 +02:00
|
|
|
func on_damage_event(event: DamageEvent) -> EventResult.ResultType:
|
|
|
|
|
if event.target != self or is_destroyed:
|
|
|
|
|
return EventResult.ResultType.KEEP_SUBSCRIPTION
|
2024-10-01 16:43:34 +02:00
|
|
|
|
2024-10-23 14:57:06 +02:00
|
|
|
apply_damage(event.damage_value)
|
2024-10-01 16:43:34 +02:00
|
|
|
|
2024-10-23 14:57:06 +02:00
|
|
|
if current_health <= 0.0:
|
|
|
|
|
emit_asteroid_destroyed()
|
|
|
|
|
return EventResult.ResultType.DISPOSE_SUBSCRIPTION
|
2024-10-01 16:43:34 +02:00
|
|
|
|
2024-10-23 14:57:06 +02:00
|
|
|
return EventResult.ResultType.KEEP_SUBSCRIPTION
|
|
|
|
|
|
|
|
|
|
func apply_damage(damage: float) -> void:
|
|
|
|
|
current_health = max(current_health - damage, 0)
|
|
|
|
|
update_health_label()
|
|
|
|
|
|
|
|
|
|
func emit_asteroid_destroyed() -> void:
|
|
|
|
|
is_destroyed = true
|
|
|
|
|
queue_free()
|
|
|
|
|
publish_destroyed_event()
|
2024-10-01 16:43:34 +02:00
|
|
|
|
2024-10-23 14:57:06 +02:00
|
|
|
func publish_destroyed_event() -> void:
|
|
|
|
|
var destroyed_event = DestroyedEvent.new(self, "asteroid", global_position, "laser")
|
|
|
|
|
event_bus.publish(get_node("/root/Main/DestroyedEventScope"), destroyed_event)
|
2024-10-01 16:43:34 +02:00
|
|
|
|
2024-10-23 14:57:06 +02:00
|
|
|
func update_health_label() -> void:
|
2024-10-01 16:43:34 +02:00
|
|
|
$AsteroidHealthLabel.text = str(round(current_health)) + " / " + str(max_health)
|