Files

192 lines
7.0 KiB
GDScript

@tool
class_name SceneryProp
extends Node2D
## Decoracion reutilizable con colision opcional e independiente de su profundidad.
## El origen esta abajo, en el centro: colocar el nodo sobre la superficie del suelo.
## Los presets de barril, farola, caja y fachadas reutilizan este mismo comportamiento.
## La colision solida, el orden visual y recibir golpes son tres ajustes independientes.
signal broken
const COMBAT_FX = preload("res://effects/combat_fx.gd")
const HURTBOX_LAYER: int = 1 << 5
@export_category("Appearance")
@export var texture: Texture2D:
set(value):
texture = value
_queue_refresh()
## Tamano visible en pixeles; no modifica la colision deliberadamente.
@export var display_size: Vector2 = Vector2(64.0, 64.0):
set(value):
display_size = Vector2(maxf(value.x, 1.0), maxf(value.y, 1.0))
_queue_refresh()
@export var tint: Color = Color.WHITE:
set(value):
tint = value
_queue_refresh()
## Solo cambia el orden de dibujo. Un objeto de fondo puede seguir siendo solido.
@export_enum("Background:-8", "Behind characters:-2", "At world depth:0", "In front of characters:10") var draw_layer: int = -2:
set(value):
draw_layer = value
_queue_refresh()
@export var flip_h: bool = false:
set(value):
flip_h = value
_queue_refresh()
@export_category("Collision")
## Activado: obstaculo solido en la capa World. Desactivado: se atraviesa.
@export var collision_enabled: bool = false:
set(value):
collision_enabled = value
_queue_refresh()
@export var collision_dimensions: Vector2 = Vector2(48.0, 56.0):
set(value):
collision_dimensions = Vector2(maxf(value.x, 1.0), maxf(value.y, 1.0))
_queue_refresh()
## Desplazamiento desde los pies; una Y negativa coloca la forma encima del suelo.
@export var collision_offset: Vector2 = Vector2(0.0, -28.0):
set(value):
collision_offset = value
_queue_refresh()
## Guia del editor; nunca se muestra durante la partida.
@export var preview_collision: bool = false:
set(value):
preview_collision = value
queue_redraw()
@export_category("Breakable")
## Desactivado conserva una decoracion normal; activado acepta ataques del jugador.
@export var breakable: bool = false:
set(value):
breakable = value
_queue_refresh()
## Resistencia. El barril usa 5: un punetazo base lo rompe.
@export_range(1, 1000, 1) var break_health: int = 5
## Arrastra una escena de pickups/variants o rare_items/variants. Vacio: no suelta nada.
## Se instancia una unica vez; no utiliza probabilidades ni la tabla de los enemigos.
@export var drop_scene: PackedScene
## Posicion local del premio respecto a los pies, no respecto a la camara.
@export var drop_offset: Vector2 = Vector2(0.0, -28.0)
var current_health: int = 0
var is_broken: bool = false
var _refresh_pending: bool = false
func _ready() -> void:
current_health = break_health
_refresh()
func _queue_refresh() -> void:
if not is_inside_tree() or _refresh_pending:
return
_refresh_pending = true
call_deferred("_refresh")
## Las formas se crean por instancia, nunca se modifica un recurso compartido.
func _refresh() -> void:
_refresh_pending = false
if not is_inside_tree() or not has_node("Visual"):
return
z_as_relative = false
z_index = draw_layer
var visual: Sprite2D = $Visual
visual.texture = texture
visual.position = Vector2(0.0, -display_size.y * 0.5)
visual.self_modulate = tint
visual.flip_h = flip_h
if texture != null:
visual.scale = display_size / texture.get_size()
var body: StaticBody2D = $Body
body.collision_layer = 1 if collision_enabled and not is_broken else 0
body.collision_mask = 0
body.position = collision_offset
var collision: CollisionShape2D = $Body/CollisionShape2D
var rectangle := RectangleShape2D.new()
rectangle.size = collision_dimensions
collision.shape = rectangle
collision.disabled = not collision_enabled or is_broken
var hurtbox: Area2D = $Hurtbox
hurtbox.position = collision_offset
hurtbox.collision_layer = HURTBOX_LAYER if breakable and not is_broken else 0
hurtbox.collision_mask = 0
hurtbox.monitorable = breakable and not is_broken
var hurt_shape := RectangleShape2D.new()
hurt_shape.size = collision_dimensions
($Hurtbox/CollisionShape2D as CollisionShape2D).shape = hurt_shape
($Hurtbox/CollisionShape2D as CollisionShape2D).disabled = not breakable or is_broken
if not Engine.is_editor_hint():
if breakable and not is_broken:
add_to_group("breakable")
elif is_in_group("breakable"):
remove_from_group("breakable")
queue_redraw()
update_configuration_warnings()
## Comparte el contrato de impacto de los enemigos, pero no emite died ni concede carga.
func take_damage(amount: int, source_position: Vector2) -> void:
if Engine.is_editor_hint() or not breakable or is_broken or amount <= 0:
return
current_health = maxi(current_health - amount, 0)
if current_health > 0:
COMBAT_FX.spawn(get_parent(), to_global(collision_offset), &"hit", signf(global_position.x - source_position.x))
return
# Este cerrojo es inmediato: dos golpes/pulsos en el mismo frame solo producen un drop.
is_broken = true
hide()
if is_in_group("breakable"):
remove_from_group("breakable")
$Body/CollisionShape2D.set_deferred("disabled", true)
$Hurtbox/CollisionShape2D.set_deferred("disabled", true)
$Hurtbox.set_deferred("monitorable", false)
call_deferred("_finish_break")
## La rotura y el alta del premio salen del callback de fisica.
## El premio es hermano del adorno: no se destruye cuando desaparece este nodo.
func _finish_break() -> void:
if not is_broken or not is_inside_tree() or is_queued_for_deletion():
return
var container: Node = get_parent()
COMBAT_FX.spawn(container, to_global(collision_offset), &"break")
if drop_scene != null:
var instance: Node = drop_scene.instantiate()
if not (instance is Pickup or instance is RarePickup):
push_warning("Drop Scene debe ser una escena de Pickup o RarePickup, no un nivel ni una decoracion.")
instance.free()
else:
var drop := instance as Node2D
var spawn_position: Vector2 = to_global(drop_offset)
drop.position = (container as Node2D).to_local(spawn_position) if container is Node2D else spawn_position
if drop is Pickup:
(drop as Pickup).collection_delay_seconds = Pickup.DROP_COLLECTION_DELAY_SECONDS
elif drop is RarePickup:
(drop as RarePickup).collection_delay_seconds = Pickup.DROP_COLLECTION_DELAY_SECONDS
container.add_child(drop)
broken.emit()
queue_free()
func _draw() -> void:
if Engine.is_editor_hint() and preview_collision:
var bounds := Rect2(collision_offset - collision_dimensions * 0.5, collision_dimensions)
var color := Color(0.25, 0.85, 1.0, 0.85) if collision_enabled else Color(1.0, 0.6, 0.25, 0.65)
draw_rect(bounds, color, false, 2.0)
func _get_configuration_warnings() -> PackedStringArray:
var warnings := PackedStringArray()
if texture == null:
warnings.append("Asigna Texture o utiliza uno de los presets de world/props.")
if not scale.is_equal_approx(Vector2.ONE):
warnings.append("Usa Display Size y Collision Dimensions; deja Scale en (1, 1).")
if drop_scene != null and not breakable:
warnings.append("Hay un Drop Scene asignado pero Breakable esta desactivado: no se soltara.")
return warnings