♻️REFACTOR: Mejoras en la viabilidad para desarrollo

This commit is contained in:
Diego De la Viuda Llorente committed 2026-10-29 13:23:46 +01:00
1 parent 5aba6c7b47
commit fd0118d964
98 files changed
+5985 -3024

No files matched your search

+133 -114
View File
@@ -1,187 +1,192 @@
extends CharacterBody2D
## Controlador del jugador: movimiento, combate y estado temporal.
## Ajustes por personaje: player/characters/*.tres; ajustes comunes: player/player.tscn.
## Mapa de funciones y criterios de ampliacion: docs/architecture.md.
signal health_changed(current_health: int, max_health: int)
signal died
signal special_charge_changed(current_charge: int, max_charge: int)
## Emitted only after an object successfully applies its effect.
## The test level uses this signal to count items actually collected.
## Solo se emite cuando el objeto ha aplicado su efecto. El laboratorio cuenta recogidas reales, no simples contactos.
signal pickup_collected(data: PickupData)
# Collision layers used by this first playable slice.
# Keeping the numbers here makes the scene setup easier to understand:
# 1 -> world
# 2 -> player body
# 3 -> enemy body
# 4 -> player hurtbox
# 5 -> enemy hurtbox
# Capas de fisica: 1 escenario, 2 cuerpo del jugador, 3 cuerpo enemigo,
# 4 zona vulnerable del jugador y 5 zona vulnerable del enemigo.
# Los bits de las mascaras empiezan en cero; no confundir bit con numero de capa.
const ENEMY_HURTBOX_MASK: int = 1 << 4
const COMBAT_FX = preload("res://effects/combat_fx.gd")
# ============================================================================
# CHARACTER
# PERSONAJE
# ============================================================================
@export_category("Character")
## Resource that identifies the selected band member and contains the stats
## that are allowed to differ between characters.
## Identidad, animaciones y estadisticas propias del integrante.
## Los ajustes comunes de movimiento y combate se editan debajo, en player.tscn.
@export var character_data: CharacterData
# ============================================================================
# MOVEMENT
# MOVIMIENTO
# ============================================================================
@export_category("Movement")
## Reaches full running speed quickly, but not instantly.
## Aceleracion horizontal en el suelo; no alcanza la velocidad maxima instantaneamente.
@export var ground_acceleration: float = 4000.0
## Used when there is no horizontal input. Slightly stronger than acceleration
## so releasing the controls feels precise instead of slippery.
## Frenado al soltar la direccion. Mayor que la aceleracion para evitar deslizamiento.
@export var ground_friction: float = 5000.0
## Braking used only when the player asks for the opposite direction. The
## character loses the old momentum first and then accelerates the other way,
## producing a small but turning is snappy enough.
## Frenado al invertir la direccion: primero elimina el impulso anterior y luego acelera al otro lado.
@export var turn_braking: float = 5800.0
## Air control stays responsive but weaker than movement on the floor.
## Control horizontal en el aire, deliberadamente menor que el del suelo.
@export var air_acceleration: float = 2000.0
# ============================================================================
# JUMP
# SALTO
# ============================================================================
@export_category("Jump")
## Allows a jump a few milliseconds after walking off a ledge.
## Margen en segundos para saltar justo despues de abandonar un borde (coyote time).
@export var coyote_time: float = 0.17
## Remembers an early jump press just before landing.
## Tiempo que se recuerda un salto pulsado poco antes de tocar suelo.
@export var jump_buffer_time: float = 0.17
## Releasing jump while rising cuts the jump short.
## Multiplicador de la velocidad ascendente al soltar salto; permite saltos cortos.
@export_range(0.1, 1.0) var jump_cut_multiplier: float = 0.43
## Escala la gravedad del proyecto durante el movimiento normal.
@export var gravity_multiplier: float = 1.0
## Multiplicador usado al descender; sustituye al normal, no se multiplica por el.
@export var fall_gravity_multiplier: float = 1.6
## Limite de velocidad descendente en pixeles por segundo.
@export var max_fall_speed: float = 1400.0
@export_category("Double Jump")
## Enables a second jump while in the air.
## Permite un segundo salto sin haber vuelto al suelo.
@export var enable_double_jump: bool = true
## Maximum number of jumps allowed (1 = only ground/coyote, 2 = double jump).
## Numero maximo de saltos: 1 en suelo/margen de borde; 2 incluye doble salto.
@export_range(1, 2, 1) var max_jumps: int = 2
## Height multiplier applied to the second jump relative to the character's jump force.
## Multiplica el impulso vertical del segundo salto, no directamente su altura en pixeles.
@export_range(0.5, 0.95, 0.01) var double_jump_multiplier: float = 0.8
# ============================================================================
# DAMAGE RECEIVED
# DANO RECIBIDO
# ============================================================================
@export_category("Damage received")
## Short grace period so a contact hitbox cannot drain all health in one frame.
## Ventana de invulnerabilidad tras un golpe; evita recibir dano en cada fotograma de contacto.
@export var invulnerability_duration: float = 0.65
## Horizontal and vertical impulse applied when the player is hit.
## Impulso horizontal y vertical al recibir dano, independiente de la velocidad de carrera.
@export var damage_knockback: Vector2 = Vector2(310.0, 270.0)
# ============================================================================
# PUNCH
# PUNETAZO
# ============================================================================
@export_category("Punch")
## Duracion visual total del punetazo en segundos.
@export var punch_duration: float = 0.28
## Tiempo antes de que el punetazo pueda causar dano.
@export var punch_windup: float = 0.055
## Ventana danina del punetazo en segundos.
@export var punch_active_duration: float = 0.11
## Espera minima entre inicios de punetazo.
@export var punch_cooldown: float = 0.34
## Cover the player's body too, so overlapping enemies can be hit from either side.
## Keep the forward edge at 42 pixels; only extend the hitbox inward.
## El area cubre tambien el cuerpo para golpear enemigos superpuestos.
## Se conserva el extremo frontal a 42 px; el area adicional se extiende hacia dentro.
@export var punch_hitbox_size: Vector2 = Vector2(56.0, 22.0)
## Centro del punetazo relativo al jugador mirando a la derecha.
@export var punch_offset: Vector2 = Vector2(14.0, -4.0)
# ============================================================================
# GROUND POUND
# GOLPE AEREO
# ============================================================================
@export_category("Ground Pound")
## Minimum downward speed when the air attack starts.
## Velocidad descendente minima al iniciar el golpe aereo.
@export var ground_pound_start_speed: float = 450.0
## Extra gravity while performing the air attack.
## Gravedad adicional mientras dura el golpe aereo.
@export var ground_pound_gravity_multiplier: float = 4.5
## Small amount of steering kept during the fall.
## Fraccion del control horizontal que se mantiene durante la caida ofensiva.
@export_range(0.0, 1.0) var ground_pound_horizontal_control: float = 0.25
## Radio del impacto al aterrizar, en pixeles.
@export var ground_pound_radius: float = 54.0
## Centro del impacto respecto al cuerpo del jugador.
@export var ground_pound_offset: Vector2 = Vector2(0.0, 24.0)
## From 7 damage on a small jump to 12 on a high one; always stronger
## than a standard 5-point punch, even without any pickup.
## Dano entre 7 y 12 segun la altura alcanzada, superior al punetazo base de 5.
## Las mejoras no permiten superar el limite final configurado.
@export var ground_pound_damage_per_pixel: float = 0.065
@export_range(1, 100, 1) var ground_pound_min_damage: int = 7
@export_range(1, 100, 1) var ground_pound_max_damage: int = 12
# ============================================================================
# SPECIAL ATTACK
# ATAQUE ESPECIAL
# ============================================================================
@export_category("Special Attack")
## Maximum charge of the special meter (0-100).
## Capacidad maxima del medidor especial, entre 0 y 100.
@export_range(0, 100, 1) var special_max_charge: int = 100
## Charge gained when an enemy dies.
## Carga que se concede al recibir la senal de muerte de un enemigo.
@export_range(0, 100, 1) var special_charge_per_kill: int = 25
## Minimum charge required to use special attack.
## Carga minima necesaria para iniciar el ataque especial.
@export_range(0, 100, 1) var special_min_use_charge: int = 25
## Maximum damage dealt by the special (at full charge, closest to player).
## Dano maximo a plena carga y a la menor distancia del jugador.
@export_range(0, 100, 1) var special_max_damage: int = 30
## Optional hard cutoff for the special. Very large = previous full-screen behaviour.
## The Level 01 test sets a smaller radius to keep encounters independent.
## Radio adicional al filtro de pantalla. Un valor grande conserva el alcance visible original.
## El laboratorio usa un radio reducido para aislar sus estaciones.
@export var special_radius: float = 100000.0
## Guitar draw, sustained solo, then recovery. Damage is shared by all pulses.
## Duracion del solo: preparacion, pulsos y recuperacion. El dano total se reparte entre los pulsos.
@export_range(0.6, 6.0, 0.1) var special_duration: float = 2.4
@export_range(1, 8, 1) var special_pulse_count: int = 4
# ============================================================================
# DEBUG
# DEPURACION
# ============================================================================
@export_category("Debug")
## Draws the actual hurtbox and attack areas used by gameplay.
## Combat effects do not depend on this debug overlay.
## Muestra las areas fisicas reales. Los efectos visibles del combate no dependen de esta opcion.
@export var show_debug_hitboxes: bool = false
## Keeps the ground-pound area visible briefly after impact.
## Tiempo que permanece visible el area de impacto despues del golpe aereo.
@export var debug_impact_duration: float = 0.18
# ============================================================================
# NODES
# NODOS
# ============================================================================
@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D
@@ -194,7 +199,7 @@ const COMBAT_FX = preload("res://effects/combat_fx.gd")
# ============================================================================
# RUNTIME STATE
# ESTADO DE LA PARTIDA
# ============================================================================
var current_health: int = 1
@@ -215,7 +220,7 @@ var jumps_remaining: int = 2
var _speed_boost_timer: float = 0.0
var _speed_boost_multiplier: float = 0.0
# Only runtime state changes: CharacterData remains immutable during pickups.
# Las mejoras solo alteran estado temporal; nunca se modifica el recurso CharacterData compartido.
var _damage_boost_timer: float = 0.0
var _damage_boost_multiplier: float = 0.0
var _air_damage_boost_timer: float = 0.0
@@ -228,14 +233,12 @@ var _shield_hits: int = 0
var _floating_texts: Array = []
# Tracks the highest point reached since leaving the ground, used to scale
# ground pound damage by jump height instead of fall distance.
# Altura maxima desde el despegue: el golpe aereo escala por altura de salto, no por distancia de caida.
var _jump_height_tracking: bool = false
var _jump_start_position: Vector2
var _jump_peak_height: float = 0.0
## Prevents one target from receiving damage every physics frame during the
## same punch. A new punch starts with an empty set again.
## Registro por ataque: cada objetivo recibe un solo impacto por punetazo, no uno por fotograma.
var punch_hit_targets: Dictionary = {}
var special_charge: int = 0
@@ -251,6 +254,7 @@ var _landing_animation_timer: float = 0.0
var _punch_swing_shown: bool = false
## Carga el personaje y prepara ataques, animacion y senales iniciales del HUD.
func _ready() -> void:
if character_data == null:
push_error("Player needs a CharacterData resource.")
@@ -267,11 +271,12 @@ func _ready() -> void:
_update_animation()
health_changed.emit(current_health, character_data.max_health)
special_charge_changed.emit(special_charge, special_max_charge)
# Conecta a los enemigos que ya estén en el árbol. Si se añaden más tarde,
# se conectarán cuando mueran mediante el grupo "enemy".
# Conecta los enemigos que ya pertenecen al grupo al iniciar el nivel.
# Un futuro sistema de aparicion dinamica debera conectar tambien sus nuevas instancias.
_connect_to_enemies()
## Orden del fotograma: entradas, movimiento, colisiones, aterrizaje y presentacion.
func _physics_process(delta: float) -> void:
if character_data == null or is_dead:
return
@@ -289,8 +294,7 @@ func _physics_process(delta: float) -> void:
move_and_slide()
# Track the highest point reached since leaving the ground, so ground pound
# damage is based on jump height rather than the current fall distance.
# Registra el punto mas alto desde el despegue para calcular el dano por altura de salto.
if not is_on_floor():
if not _jump_height_tracking:
_jump_height_tracking = true
@@ -301,7 +305,7 @@ func _physics_process(delta: float) -> void:
elif _jump_height_tracking:
_jump_height_tracking = false
# Landing is only reliable after move_and_slide() has resolved collisions.
# El aterrizaje solo es fiable despues de resolver colisiones con move_and_slide().
if not was_on_floor and is_on_floor():
jumps_remaining = max_jumps
if ground_pound_active:
@@ -317,11 +321,12 @@ func _physics_process(delta: float) -> void:
# ============================================================================
# MOVEMENT
# MOVIMIENTO
# ============================================================================
## Combina aceleracion, frenado, control aereo y retroceso sin cambiar el limite de velocidad.
func _handle_horizontal_movement(delta: float) -> void:
# Let impulses decay instead of immediately overwriting them with input.
# Durante el retroceso se conserva y amortigua el impulso, en lugar de anularlo con la entrada.
if _special_active or _hurt_animation_timer > 0.0:
var braking: float = 110.0 if _special_active else 550.0
velocity.x = move_toward(velocity.x, 0.0, braking * delta)
@@ -347,9 +352,7 @@ func _handle_horizontal_movement(delta: float) -> void:
if direction == 0.0:
velocity.x = move_toward(velocity.x, 0.0, ground_friction * delta)
elif velocity.x != 0.0 and signf(velocity.x) != signf(direction):
# Do not snap directly from full speed right to full speed left. Brake
# the previous momentum first; on the next frames normal acceleration
# takes over in the requested direction.
# Al invertir la direccion primero se frena; los siguientes fotogramas aplican la aceleracion normal.
velocity.x = move_toward(velocity.x, 0.0, turn_braking * delta)
else:
velocity.x = move_toward(
@@ -361,8 +364,7 @@ func _handle_horizontal_movement(delta: float) -> void:
velocity.x = move_toward(velocity.x, target_speed, air_acceleration * delta)
## Horizontal running speed with active pickups applied. Keeping the HUD and
## movement on the same calculation avoids showing a bonus that isn't used.
## Velocidad efectiva incluyendo mejoras. HUD y movimiento usan este mismo calculo.
func get_move_speed() -> float:
if character_data == null:
return 0.0
@@ -370,11 +372,11 @@ func get_move_speed() -> float:
return character_data.move_speed * (1.0 + bonus)
## Refleja imagen y areas de ataque segun la direccion actual.
func _update_facing() -> void:
animated_sprite.flip_h = facing_direction < 0.0
# Only the horizontal offset changes when turning around. The hitbox size
# stays identical for both directions.
# Al girar solo se refleja el desplazamiento horizontal; el tamano del ataque no cambia.
punch_hitbox.position = Vector2(
abs(punch_offset.x) * facing_direction,
punch_offset.y
@@ -382,9 +384,10 @@ func _update_facing() -> void:
# ============================================================================
# GRAVITY AND JUMP
# GRAVEDAD Y SALTO
# ============================================================================
## Distingue ascenso, caida normal y caida ofensiva; limita la velocidad vertical.
func _apply_gravity(delta: float) -> void:
if is_on_floor():
return
@@ -401,6 +404,7 @@ func _apply_gravity(delta: float) -> void:
velocity.y = min(velocity.y, max_fall_speed)
## Actualiza el margen de borde, la memoria de entrada y los saltos restantes.
func _update_jump_windows(delta: float) -> void:
if is_on_floor():
coyote_timer = coyote_time
@@ -414,6 +418,7 @@ func _update_jump_windows(delta: float) -> void:
jump_buffer_timer = max(jump_buffer_timer - delta, 0.0)
## Consume el salto permitido y aplica impulso variable al soltar el boton.
func _handle_jump() -> void:
if _special_active or _hurt_animation_timer > 0.0:
return
@@ -436,9 +441,10 @@ func _handle_jump() -> void:
# ============================================================================
# ATTACK INPUT
# ENTRADA DE ATAQUES
# ============================================================================
## Decide que ataque puede iniciarse con la entrada y el estado actuales.
func _handle_attack_input() -> void:
if _special_active or _hurt_animation_timer > 0.0:
return
@@ -447,8 +453,7 @@ func _handle_attack_input() -> void:
return
if Input.is_action_just_pressed("ground_pound"):
# The ground pound is an air attack: it only triggers while jumping or
# falling, so it never replaces a grounded punch.
# El golpe aereo solo comienza en el aire; no reemplaza un punetazo desde el suelo.
if not is_on_floor():
_start_ground_pound()
return
@@ -459,9 +464,10 @@ func _handle_attack_input() -> void:
# ============================================================================
# PUNCH
# PUNETAZO
# ============================================================================
## Inicia una ventana de punetazo y vacia el registro de objetivos ya golpeados.
func _start_punch() -> void:
if is_dead or _special_active or ground_pound_active or attack_cooldown_timer > 0.0:
return
@@ -471,6 +477,7 @@ func _start_punch() -> void:
punch_hit_targets.clear()
## Aplica impactos solo durante la fase activa del punetazo.
func _update_punch_damage() -> void:
if punch_timer <= 0.0:
return
@@ -486,9 +493,10 @@ func _update_punch_damage() -> void:
# ============================================================================
# GROUND POUND
# GOLPE AEREO
# ============================================================================
## Cancela el ascenso y prepara el ataque de caida.
func _start_ground_pound() -> void:
if is_dead or _special_active or ground_pound_active:
return
@@ -497,11 +505,11 @@ func _start_ground_pound() -> void:
ground_pound_active = true
attack_cooldown_timer = punch_cooldown
# If the player is still rising, the attack immediately turns the movement
# into a fall instead of waiting for the jump apex.
# Si aun estaba ascendiendo, convierte inmediatamente el salto en caida ofensiva.
velocity.y = max(velocity.y, ground_pound_start_speed)
## Calcula el dano y consulta objetivos en la posicion final del aterrizaje.
func _ground_pound_impact() -> void:
ground_pound_active = false
ground_pound_debug_timer = debug_impact_duration
@@ -510,8 +518,7 @@ func _ground_pound_impact() -> void:
&"ground_pound", facing_direction, ground_pound_radius)
feedback_camera.call("impact", 2.8, 0.24)
# Damage scales with jump height: how high the player rose from the takeoff
# point, clamped between the min and max damage.
# Calcula el dano a partir de la altura maxima sobre el punto de despegue y aplica sus limites.
var height_reached: float = _jump_start_position.y - _jump_peak_height
if height_reached < 0.0:
height_reached = 0.0
@@ -524,13 +531,12 @@ func _ground_pound_impact() -> void:
var hit_targets: Dictionary = {}
# The final damage is capped too: active buffs make the 12-point ceiling
# easier to reach, rather than turning an alpha attack into a one-shot.
# El limite se aplica tambien tras las mejoras: facilitan alcanzar el maximo, pero no lo superan.
var final_damage: int = mini(
roundi(damage * (1.0 + _damage_boost_multiplier + _air_damage_boost_multiplier)),
ground_pound_max_damage
)
# Query at the resolved landing position, not last frame's cached overlaps.
# Consulta la fisica en la posicion de aterrizaje ya resuelta, no los contactos del fotograma anterior.
var query := PhysicsShapeQueryParameters2D.new()
query.shape = ground_pound_collision.shape
query.transform = ground_pound_collision.global_transform
@@ -542,9 +548,10 @@ func _ground_pound_impact() -> void:
# ============================================================================
# SPECIAL ATTACK
# ATAQUE ESPECIAL
# ============================================================================
## Consume la carga disponible e inicializa el reparto de dano por pulsos.
func _start_special_attack() -> void:
if is_dead or _special_active or ground_pound_active or special_max_charge <= 0:
return
@@ -565,6 +572,7 @@ func _start_special_attack() -> void:
_spawn_floating_text("GUITAR SOLO!", Color(0.76, 0.85, 1.0))
## Avanza las fases visuales del solo y emite cada pulso una sola vez.
func _update_special_attack(delta: float) -> void:
if not _special_active:
return
@@ -572,7 +580,7 @@ func _update_special_attack(delta: float) -> void:
var pulse_count: int = maxi(special_pulse_count, 1)
var windup: float = special_duration * 0.15
var interval: float = special_duration * 0.65 / float(maxi(pulse_count - 1, 1))
# Catch up when a long frame spans a pulse, without replaying previous pulses.
# Un fotograma largo puede abarcar varios pulsos; se recuperan los pendientes sin repetir los anteriores.
while _special_pulses_sent < pulse_count:
if _special_elapsed < windup + interval * float(_special_pulses_sent):
break
@@ -588,6 +596,7 @@ func _update_special_attack(delta: float) -> void:
_special_damage_dealt.clear()
## Mantiene un presupuesto de dano por enemigo para no multiplicarlo por el numero de pulsos.
func _apply_special_attack(charge_used: int, pulse_index: int = 0) -> void:
var charge_ratio: float = clampf(float(charge_used) / float(maxi(special_max_charge, 1)), 0.0, 1.0)
var viewport_rect: Rect2 = get_viewport().get_visible_rect()
@@ -601,7 +610,7 @@ func _apply_special_attack(charge_used: int, pulse_index: int = 0) -> void:
var distance: float = global_position.distance_to(enemy.global_position)
if special_radius > 0.0 and distance > special_radius:
continue
# A screen attack should not silently damage enemies at the far end of the map.
# Solo afecta a enemigos visibles; no debe golpear a distancia al otro extremo del mapa.
if not viewport_rect.grow(28.0).has_point(enemy.get_global_transform_with_canvas().origin):
continue
@@ -609,7 +618,7 @@ func _apply_special_attack(charge_used: int, pulse_index: int = 0) -> void:
if not _special_damage_budgets.has(enemy_id):
var distance_factor: float = maxf(0.1, 1.0 - clampf(distance / max_distance, 0.0, 1.0))
_special_damage_budgets[enemy_id] = maxi(1, int(special_max_damage * charge_ratio * distance_factor))
# Freeze the budget on first contact: knockback must not change total damage.
# Fija el presupuesto al primer contacto: el retroceso posterior no cambia el dano total.
var total_damage: int = int(_special_damage_budgets[enemy_id])
var cumulative_damage: int = ceili(float(total_damage) * float(pulse_index + 1) / float(pulse_count))
var damage: int = cumulative_damage - int(_special_damage_dealt.get(enemy_id, 0))
@@ -619,6 +628,7 @@ func _apply_special_attack(charge_used: int, pulse_index: int = 0) -> void:
enemy.call("take_damage", damage, global_position)
## Devuelve true solo si se aplica el efecto. False conserva el objeto para otra oportunidad.
func collect_pickup(data: PickupData) -> bool:
if is_dead or data == null or character_data == null:
return false
@@ -640,7 +650,7 @@ func collect_pickup(data: PickupData) -> bool:
"damage_boost", "air_damage_boost", "damage_reduction", "jump_boost":
if data.value <= 0.0 or data.duration <= 0.0:
return false
# Repeated pickup refreshes time and keeps the strongest bonus.
# Recoger la misma mejora renueva el tiempo y conserva la potencia mas alta.
match data.effect_type:
"damage_boost":
_damage_boost_multiplier = max(_damage_boost_multiplier, data.value) if _damage_boost_timer > 0.0 else data.value
@@ -674,6 +684,7 @@ func collect_pickup(data: PickupData) -> bool:
return true
## Registra un mensaje visual sin crear nodos por cada aviso.
func _spawn_floating_text(text: String, color: Color) -> void:
var entry := {
"text": text,
@@ -685,6 +696,7 @@ func _spawn_floating_text(text: String, color: Color) -> void:
_floating_texts.append(entry)
## Mueve y elimina los mensajes cuyo tiempo de vida se ha agotado.
func _update_floating_texts(delta: float) -> void:
for entry in _floating_texts:
entry.pos += entry.velocity * delta
@@ -692,14 +704,16 @@ func _update_floating_texts(delta: float) -> void:
_floating_texts = _floating_texts.filter(func(e): return e.timer > 0.0)
## Suscribe las muertes de los enemigos presentes para recargar el especial.
func _connect_to_enemies() -> void:
for enemy in get_tree().get_nodes_in_group("enemy"):
if is_instance_valid(enemy) and enemy.has_signal(&"died"):
# The group yields Node references, not a statically typed Walker.
# Node.connect also works with any future enemy exposing this signal.
# El grupo entrega Node, no una clase concreta de enemigo.
# La senal permite mantener el contrato sin depender del controlador Walker.
enemy.connect(&"died", _on_enemy_died.bind(enemy))
## Suma carga sin superar su capacidad maxima y notifica al HUD.
func _on_enemy_died(_enemy: Node) -> void:
if is_dead:
return
@@ -709,14 +723,14 @@ func _on_enemy_died(_enemy: Node) -> void:
# ============================================================================
# DEALING AND RECEIVING DAMAGE
# APLICACION Y RECEPCION DE DANO
# ============================================================================
## Resuelve la entidad de una zona vulnerable y evita impactos duplicados del mismo ataque.
func _damage_target(collider: Node, damage: int, hit_targets: Dictionary) -> void:
var target: Node = collider
# Hurtboxes are Area2D children. Damage belongs to the entity that owns the
# hurtbox, so we ask the parent for take_damage().
# Las zonas vulnerables son areas hijas; el metodo de dano pertenece a la entidad que las contiene.
if not target.has_method("take_damage"):
target = target.get_parent()
@@ -731,6 +745,7 @@ func _damage_target(collider: Node, damage: int, hit_targets: Dictionary) -> voi
target.take_damage(damage, global_position)
## Valida invulnerabilidad y escudo antes de reducir vida, aplicar empuje y comprobar muerte.
func take_damage(amount: int, source_position: Vector2, knockback_multiplier: float = 1.0) -> void:
if amount <= 0 or is_dead or invulnerability_timer > 0.0:
return
@@ -741,20 +756,18 @@ func take_damage(amount: int, source_position: Vector2, knockback_multiplier: fl
_spawn_floating_text("BLOCK!", Color(0.7, 0.9, 1.0))
return
# At least one point of damage passes through an active reduction.
# La reduccion de dano conserva al menos un punto por impacto.
if _damage_reduction_timer > 0.0:
amount = maxi(1, roundi(amount * (1.0 - clampf(_damage_reduction_fraction, 0.0, 0.95))))
current_health = max(current_health - amount, 0)
invulnerability_timer = invulnerability_duration
# Knock the player away from the source. If both centers are aligned, use
# the opposite of the current facing direction as a deterministic fallback.
# Empuja alejandose del origen. Si los centros coinciden, usa la direccion contraria a la mirada.
var knockback_direction: float = signf(global_position.x - source_position.x)
if knockback_direction == 0.0:
knockback_direction = -facing_direction
# Enemy variants choose their push independently of HP damage. Existing
# two-argument calls (hazards, tests) retain the original impulse.
# Cada enemigo ajusta su empuje sin cambiar el dano. Las llamadas antiguas de dos argumentos conservan su fuerza.
var push_scale: float = clampf(knockback_multiplier, 0.0, 3.0)
velocity.x = knockback_direction * damage_knockback.x * push_scale
velocity.y = -damage_knockback.y * sqrt(push_scale)
@@ -770,25 +783,27 @@ func take_damage(amount: int, source_position: Vector2, knockback_multiplier: fl
_die()
## Detiene el especial, emite la muerte y solicita la recarga fuera del paso de fisica.
func _die() -> void:
is_dead = true
_special_active = false
feedback_camera.call("start_solo", 0.0)
died.emit()
# Reloading from a deferred call avoids changing the scene tree while a
# physics overlap is still being processed.
# La recarga se difiere para no destruir el arbol mientras la fisica procesa un contacto.
call_deferred("_reload_level")
## Reinicia la escena actual; no selecciona ni desbloquea niveles.
func _reload_level() -> void:
get_tree().reload_current_scene()
# ============================================================================
# TIMERS AND ANIMATION
# TEMPORIZADORES Y ANIMACION
# ============================================================================
## Hace caducar ataques, invulnerabilidad y mejoras temporales de forma independiente.
func _update_timers(delta: float) -> void:
_hurt_animation_timer = maxf(0.0, _hurt_animation_timer - delta)
_landing_animation_timer = maxf(0.0, _landing_animation_timer - delta)
@@ -800,7 +815,7 @@ func _update_timers(delta: float) -> void:
_speed_boost_timer = max(_speed_boost_timer - delta, 0.0)
else:
_speed_boost_multiplier = 0.0
# Each effect expires independently; no mutation of the character resource.
# Cada mejora caduca por separado; nunca se muta el recurso de personaje.
_damage_boost_timer = maxf(0.0, _damage_boost_timer - delta)
_air_damage_boost_timer = maxf(0.0, _air_damage_boost_timer - delta)
_damage_reduction_timer = maxf(0.0, _damage_reduction_timer - delta)
@@ -815,6 +830,7 @@ func _update_timers(delta: float) -> void:
_jump_boost_multiplier = 0.0
## Selecciona la animacion con prioridad de estados; admite conjuntos de animaciones incompletos.
func _update_animation() -> void:
var animation_name: StringName = &"idle"
if _special_active:
@@ -837,16 +853,17 @@ func _update_animation() -> void:
elif absf(velocity.x) > 10.0:
animation_name = &"walk"
# Custom CharacterData can still provide a smaller animation set.
# Un personaje personalizado puede aportar menos animaciones; se mantiene una alternativa valida.
if not animated_sprite.sprite_frames.has_animation(animation_name):
animation_name = &"idle"
if animated_sprite.animation != animation_name or not animated_sprite.is_playing():
# Finished one-shot animations hold their last frame until the state changes.
# Una animacion no repetitiva conserva su ultimo fotograma hasta que cambia el estado.
if animated_sprite.animation == animation_name and animated_sprite.frame > 0:
return
animated_sprite.play(animation_name)
## Aplica deformacion y desplazamientos visuales sin alterar el cuerpo fisico.
func _update_visual_feedback() -> void:
if _hurt_animation_timer > 0.10:
animated_sprite.self_modulate = Color(1.8, 1.8, 1.8)
@@ -857,9 +874,10 @@ func _update_visual_feedback() -> void:
# ============================================================================
# HITBOX SETUP
# CONFIGURACION DE AREAS DE ATAQUE
# ============================================================================
## Crea formas propias de esta instancia usando las medidas editables del Inspector.
func _setup_attack_hitboxes() -> void:
var punch_shape: RectangleShape2D = RectangleShape2D.new()
punch_shape.size = punch_hitbox_size
@@ -878,16 +896,17 @@ func _setup_attack_hitboxes() -> void:
# ============================================================================
# DEBUG HITBOX DRAWING
# DIBUJO DE COLISIONES PARA DEPURACION
# ============================================================================
## Dibuja mensajes y, cuando se solicita, las areas reales de combate.
func _draw() -> void:
if is_on_floor():
draw_rect(Rect2(-14, 24, 28, 3), Color(0.05, 0.06, 0.10, 0.25))
if ground_pound_active:
for side: float in [-1.0, 1.0]:
draw_line(Vector2(17 * side, -30), Vector2(17 * side, -9), Color(1.0, 0.8, 0.45, 0.75), 2.0)
# Pickup messages remain visible when collision debugging is disabled.
# Los mensajes de objetos se muestran aunque este desactivada la depuracion de colisiones.
var font: Font = ThemeDB.get_default_theme().get_font("font", "Label")
if font != null:
for entry: Dictionary in _floating_texts:
@@ -897,14 +916,14 @@ func _draw() -> void:
if not show_debug_hitboxes:
return
# Player hurtbox: always visible and deliberately subtle.
# Zona vulnerable del jugador, mostrada con baja opacidad.
_draw_rectangle_collision(
hurtbox_collision,
Color(1.0, 0.08, 0.08, 0.10),
Color(1.0, 0.08, 0.08, 0.45)
)
# Punch: only visible while it can actually deal damage.
# El punetazo solo se dibuja mientras puede causar dano.
if punch_timer > 0.0:
_draw_rectangle_collision(
punch_collision,
@@ -913,8 +932,7 @@ func _draw() -> void:
punch_hitbox.position
)
# Ground pound: show the real damage radius throughout the fall, then make
# it stronger for a few frames at the exact impact moment.
# Muestra el radio real durante la caida y lo resalta brevemente al impactar.
if ground_pound_active or ground_pound_debug_timer > 0.0:
var pound_fill_alpha: float = 0.14 if ground_pound_active else 0.28
var pound_outline_alpha: float = 0.60 if ground_pound_active else 0.95
@@ -933,7 +951,7 @@ func _draw() -> void:
2.0
)
# Special: show full-screen effect indication. Brighter when fully charged.
# Indicador visual del especial, mas intenso con carga completa.
var fill_alpha: float = 0.05
var outline_alpha: float = 0.25
if special_charge >= special_min_use_charge:
@@ -958,6 +976,7 @@ func _draw() -> void:
## Convierte una forma rectangular local a un rectangulo de depuracion.
func _draw_rectangle_collision(
collision: CollisionShape2D,
fill_color: Color,