Files
mortal-maze-the-game/player/player.gd
T

1065 lines
41 KiB
GDScript

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)
## Solo se emite cuando el objeto aplica su efecto, nunca por un simple contacto.
signal pickup_collected(data: PickupData)
# Capas de fisica: 1 escenario, 2 cuerpo del jugador, 3 cuerpo enemigo,
# 4 zona vulnerable del jugador, 5 del enemigo y 6 de objetos rompibles.
# Los bits de las mascaras empiezan en cero; no confundir bit con numero de capa.
const WORLD_MASK: int = 1 << 0
const ENEMY_HURTBOX_MASK: int = 1 << 4
const BREAKABLE_HURTBOX_MASK: int = 1 << 5
const COMBAT_FX = preload("res://effects/combat_fx.gd")
# ============================================================================
# PERSONAJE
# ============================================================================
@export_category("Character")
## 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
# ============================================================================
# MOVIMIENTO
# ============================================================================
@export_category("Movement")
## Aceleracion horizontal en el suelo; no alcanza la velocidad maxima instantaneamente.
@export var ground_acceleration: float = 2000.0
## Frenado al soltar la direccion. Mayor que la aceleracion para evitar deslizamiento.
@export var ground_friction: float = 3200.0
## Frenado al invertir la direccion: primero elimina el impulso anterior y luego acelera al otro lado.
@export var turn_braking: float = 3800.0
## Control horizontal en el aire, deliberadamente menor que el del suelo.
@export var air_acceleration: float = 1100.0
# ============================================================================
# SALTO
# ============================================================================
@export_category("Jump")
## Margen en segundos para saltar justo despues de abandonar un borde (coyote time).
@export var coyote_time: float = 0.17
## Tiempo que se recuerda un salto pulsado poco antes de tocar suelo.
@export var jump_buffer_time: float = 0.17
## 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")
## Permite un segundo salto sin haber vuelto al suelo.
@export var enable_double_jump: bool = true
## Numero maximo de saltos: 1 en suelo/margen de borde; 2 incluye doble salto.
@export_range(1, 2, 1) var max_jumps: int = 2
## 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
# ============================================================================
# DANO RECIBIDO
# ============================================================================
@export_category("Damage received")
## Ventana de invulnerabilidad tras un golpe; evita recibir dano en cada fotograma de contacto.
@export var invulnerability_duration: float = 0.65
## Impulso horizontal y vertical al recibir dano, independiente de la velocidad de carrera.
@export var damage_knockback: Vector2 = Vector2(310.0, 270.0)
# ============================================================================
# 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_range(0.28, 2.0, 0.01) var punch_cooldown: float = 0.60
## 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)
# ============================================================================
# GOLPE AEREO
# ============================================================================
@export_category("Ground Pound")
## Tiempo entre golpes aereos; comienza al lanzarse, incluso si se interrumpe.
@export_range(0.0, 20.0, 0.1) var ground_pound_cooldown: float = 7.0
## Velocidad descendente minima al iniciar el golpe aereo.
@export var ground_pound_start_speed: float = 450.0
## Gravedad adicional mientras dura el golpe aereo.
@export var ground_pound_gravity_multiplier: float = 4.5
## 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 comun en pixeles: 108, el doble del anterior (54), para toda la banda.
## El circulo fisico y el efecto comparten este alcance; no depende del personaje.
@export var ground_pound_radius: float = 108.0
## Centro del impacto respecto al cuerpo del jugador.
@export var ground_pound_offset: Vector2 = Vector2(0.0, 24.0)
## 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
# ============================================================================
# ATAQUE ESPECIAL
# ============================================================================
@export_category("Special Attack")
## Capacidad maxima del medidor especial, entre 0 y 100.
@export_range(0, 100, 1) var special_max_charge: int = 100
## Puntos por baja: con capacidad 100, diez bajas llenan el medidor desde cero.
@export_range(0, 100, 1) var special_charge_per_kill: int = 10
## Desactivado evita que el solo se pague a si mismo al eliminar grupos de enemigos.
## Solo filtra bajas causadas por su dano, no otras muertes que coincidan durante el solo.
@export var special_kills_grant_charge: bool = false
## Carga minima necesaria para iniciar el ataque especial.
@export_range(0, 100, 1) var special_min_use_charge: int = 25
## Dano maximo a plena carga y a la menor distancia del jugador.
@export_range(0, 100, 1) var special_max_damage: int = 30
## Radio fisico en unidades de mundo, independiente del zoom y tamano de pantalla.
## No se permite superar los 290 px para evitar golpes a traves de niveles enteros.
@export_range(1.0, 290.0, 1.0) var special_radius: float = 290.0
## 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
# ============================================================================
# DEPURACION
# ============================================================================
@export_category("Debug")
## Muestra las areas fisicas reales. Los efectos visibles del combate no dependen de esta opcion.
@export var show_debug_hitboxes: bool = false
## Tiempo que permanece visible el area de impacto despues del golpe aereo.
@export var debug_impact_duration: float = 0.18
# ============================================================================
# NODOS
# ============================================================================
@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D
@onready var feedback_camera: Camera2D = $Camera2D
@onready var hurtbox_collision: CollisionShape2D = $Hurtbox/CollisionShape2D
@onready var punch_hitbox: Area2D = $PunchHitbox
@onready var punch_collision: CollisionShape2D = $PunchHitbox/CollisionShape2D
@onready var ground_pound_hitbox: Area2D = $GroundPoundHitbox
@onready var ground_pound_collision: CollisionShape2D = $GroundPoundHitbox/CollisionShape2D
# ============================================================================
# ESTADO DE LA PARTIDA
# ============================================================================
# Copia de los bonos confirmados al iniciar el intento. No se toca CharacterData.
var _permanent_special_damage_bonus: float = 0.0
var _permanent_basic_damage_bonus: float = 0.0
var _permanent_max_health_bonus: int = 0
var current_health: int = 1
var facing_direction: float = 1.0
var coyote_timer: float = 0.0
var jump_buffer_timer: float = 0.0
var invulnerability_timer: float = 0.0
var punch_timer: float = 0.0
var attack_cooldown_timer: float = 0.0
var ground_pound_cooldown_timer: float = 0.0
var ground_pound_active: bool = false
var ground_pound_debug_timer: float = 0.0
var is_dead: bool = false
var jumps_remaining: int = 2
var _speed_boost_timer: float = 0.0
var _speed_boost_multiplier: float = 0.0
# Las mejoras solo alteran estado de la partida; nunca se modifica CharacterData.
# Las dos mejoras de dano no caducan por tiempo: se pierden al recibir un golpe valido.
var _damage_boost_multiplier: float = 0.0
var _air_damage_boost_multiplier: float = 0.0
var _damage_reduction_timer: float = 0.0
var _damage_reduction_fraction: float = 0.0
var _jump_boost_timer: float = 0.0
var _jump_boost_multiplier: float = 0.0
var _shield_hits: int = 0
var _floating_texts: Array = []
# 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
## 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
var _special_active: bool = false
# Contexto sincronico del dano: Walker emite died dentro de take_damage.
var _applying_special_damage: bool = false
var _special_elapsed: float = 0.0
var _special_charge_used: int = 0
var _special_pulses_sent: int = 0
var _special_damage_budgets: Dictionary = {}
var _special_damage_dealt: Dictionary = {}
var _hurt_animation_timer: float = 0.0
var _landing_animation_timer: float = 0.0
# Pose exclusiva del impacto ofensivo; un aterrizaje normal sigue usando land.
var _pound_landing_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:
# Resuelve la eleccion antes de vida, animaciones y senales iniciales del HUD.
var session: RunSessionState = get_node_or_null("/root/RunSession") as RunSessionState
if session != null:
var selected: CharacterData = session.character_for(self)
if selected != null:
character_data = selected
if character_data == null:
push_error("Player needs a CharacterData resource.")
return
var progress: PlayerProgressStore = get_node_or_null("/root/PlayerProgress") as PlayerProgressStore
if progress != null:
_permanent_special_damage_bonus = progress.get_total_bonus(&"special_damage_bonus")
_permanent_basic_damage_bonus = progress.get_total_bonus(&"basic_damage_bonus")
_permanent_max_health_bonus = roundi(progress.get_total_bonus(&"max_health_bonus"))
current_health = get_max_health()
if character_data.sprite_frames != null:
animated_sprite.sprite_frames = character_data.sprite_frames
jumps_remaining = max_jumps
_setup_attack_hitboxes()
_update_facing()
_update_animation()
health_changed.emit(current_health, get_max_health())
special_charge_changed.emit(special_charge, special_max_charge)
# 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
var was_on_floor: bool = is_on_floor()
_update_timers(delta)
_update_jump_windows(delta)
_handle_attack_input()
_handle_jump()
_apply_gravity(delta)
_handle_horizontal_movement(delta)
_update_punch_damage()
_update_floating_texts(delta)
move_and_slide()
# 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
_jump_start_position = global_position
_jump_peak_height = global_position.y
else:
_jump_peak_height = min(_jump_peak_height, global_position.y)
elif _jump_height_tracking:
_jump_height_tracking = false
# 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:
_ground_pound_impact()
else:
_landing_animation_timer = 0.18
COMBAT_FX.spawn(get_parent(), global_position + Vector2(0, 26), &"dust")
_update_special_attack(delta)
_update_animation()
_update_visual_feedback()
queue_redraw()
# ============================================================================
# MOVIMIENTO
# ============================================================================
## Combina aceleracion, frenado, control aereo y retroceso sin cambiar el limite de velocidad.
func _handle_horizontal_movement(delta: float) -> void:
# 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)
return
var direction: float = Input.get_axis("move_left", "move_right")
if direction != 0.0 and punch_timer <= 0.0:
facing_direction = signf(direction)
_update_facing()
var target_speed: float = direction * get_move_speed()
if ground_pound_active:
target_speed *= ground_pound_horizontal_control
velocity.x = move_toward(
velocity.x,
target_speed,
air_acceleration * delta
)
return
if is_on_floor():
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):
# 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(
velocity.x,
target_speed,
ground_acceleration * delta
)
else:
velocity.x = move_toward(velocity.x, target_speed, air_acceleration * delta)
## Velocidad efectiva incluyendo mejoras. HUD y movimiento usan este mismo calculo.
func get_move_speed() -> float:
if character_data == null:
return 0.0
var bonus: float = _speed_boost_multiplier if _speed_boost_timer > 0.0 else 0.0
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
# 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
)
# ============================================================================
# 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
var gravity: Vector2 = get_gravity()
var multiplier: float = gravity_multiplier
if ground_pound_active:
multiplier = ground_pound_gravity_multiplier
elif velocity.y > 0.0:
multiplier = fall_gravity_multiplier
velocity += gravity * multiplier * delta
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
jumps_remaining = max_jumps
else:
coyote_timer = max(coyote_timer - delta, 0.0)
if Input.is_action_just_pressed("jump"):
jump_buffer_timer = jump_buffer_time
else:
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
if (
jump_buffer_timer > 0.0
and not ground_pound_active
):
if is_on_floor() or coyote_timer > 0.0:
velocity.y = character_data.jump_velocity * (1.0 + _jump_boost_multiplier)
jump_buffer_timer = 0.0
coyote_timer = 0.0
jumps_remaining = max(0, max_jumps - 1)
elif enable_double_jump and jumps_remaining > 0:
velocity.y = character_data.jump_velocity * (1.0 + _jump_boost_multiplier) * double_jump_multiplier
jump_buffer_timer = 0.0
jumps_remaining -= 1
if Input.is_action_just_released("jump") and velocity.y < 0.0:
velocity.y *= jump_cut_multiplier
# ============================================================================
# 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
if Input.is_action_just_pressed("attack"):
_start_punch()
return
if Input.is_action_just_pressed("ground_pound"):
# El golpe aereo solo comienza en el aire; no reemplaza un punetazo desde el suelo.
if not is_on_floor():
_start_ground_pound()
return
if Input.is_action_just_pressed("special_attack"):
_start_special_attack()
return
# ============================================================================
# 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
punch_timer = punch_duration
attack_cooldown_timer = maxf(punch_cooldown, punch_duration)
_punch_swing_shown = false
punch_hit_targets.clear()
## Aplica impactos solo durante la fase activa del punetazo.
func _update_punch_damage() -> void:
if punch_timer <= 0.0:
return
var elapsed: float = punch_duration - punch_timer
if elapsed < punch_windup or elapsed > punch_windup + punch_active_duration:
return
if not _punch_swing_shown:
_punch_swing_shown = true
COMBAT_FX.spawn(get_parent(), punch_hitbox.global_position, &"swing", facing_direction)
for area in punch_hitbox.get_overlapping_areas():
_damage_target(area, get_basic_attack_damage(), punch_hit_targets, true)
# ============================================================================
# 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 or ground_pound_cooldown_timer > 0.0:
return
ground_pound_cooldown_timer = ground_pound_cooldown
punch_timer = 0.0
ground_pound_active = true
attack_cooldown_timer = punch_cooldown
# 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
_pound_landing_timer = 0.28
# La pose especifica no reemplaza la animacion de un salto normal.
if animated_sprite.sprite_frames.has_animation(&"pound_land"):
animated_sprite.play(&"pound_land")
animated_sprite.set_frame_and_progress(0, 0.0)
COMBAT_FX.spawn(get_parent(), global_position + Vector2(0, 26),
StringName(character_data.ground_pound_effect), facing_direction, ground_pound_radius)
feedback_camera.call("impact", 2.8, 0.24)
# 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
var damage: int = clamp(
int(height_reached * ground_pound_damage_per_pixel),
ground_pound_min_damage,
ground_pound_max_damage
)
var hit_targets: Dictionary = {}
# 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
)
# 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
query.collision_mask = ENEMY_HURTBOX_MASK | BREAKABLE_HURTBOX_MASK
query.collide_with_areas = true
query.collide_with_bodies = false
for hit: Dictionary in get_world_2d().direct_space_state.intersect_shape(query, 64):
_damage_target(hit["collider"], final_damage, hit_targets)
# ============================================================================
# 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
if special_charge <= 0 or special_charge < special_min_use_charge:
return
_special_charge_used = special_charge
special_charge = 0
special_charge_changed.emit(special_charge, special_max_charge)
_special_active = true
_special_elapsed = 0.0
_special_pulses_sent = 0
_special_damage_budgets.clear()
_special_damage_dealt.clear()
punch_timer = 0.0
velocity.x = 0.0
feedback_camera.call("start_solo", special_duration, character_data.special_color)
_spawn_floating_text(character_data.special_label, character_data.special_color)
## 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
_special_elapsed += delta
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))
# 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
_apply_special_attack(_special_charge_used, _special_pulses_sent)
_special_pulses_sent += 1
# Cada nota grave visible coincide con su pulso y sacudida, no con un temporizador aparte.
if character_data.special_effect == "bass_pulse":
animated_sprite.play(&"special")
animated_sprite.set_frame_and_progress(0, 0.0)
var effect_radius: float = clampf(special_radius, 1.0, 290.0)
COMBAT_FX.spawn(get_parent(), global_position,
StringName(character_data.special_effect), facing_direction, effect_radius)
# Un movimiento de camara por pulso; los platos y ondas nunca aplican dano adicional.
feedback_camera.call("impact", character_data.special_shake_strength,
character_data.special_shake_duration, character_data.special_color,
character_data.special_shake_frequency)
velocity.x = -facing_direction * 35.0
if _special_elapsed >= special_duration:
_special_active = false
_special_damage_budgets.clear()
_special_damage_dealt.clear()
## Mantiene un presupuesto de dano por objetivo 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 radius: float = clampf(special_radius, 1.0, 290.0)
var pulse_count: int = maxi(special_pulse_count, 1)
var targets: Array[Node] = get_tree().get_nodes_in_group("enemy")
targets.append_array(get_tree().get_nodes_in_group("breakable"))
for node: Node in targets:
var target := node as Node2D
if target == null or not target.has_method("take_damage") or (target.is_in_group("enemy") and bool(target.get("is_dead"))):
continue
var distance: float = global_position.distance_to(target.global_position)
if distance > radius:
continue
var target_id: int = target.get_instance_id()
if not _special_damage_budgets.has(target_id):
var distance_factor: float = maxf(0.1, 1.0 - clampf(distance / radius, 0.0, 1.0))
_special_damage_budgets[target_id] = maxi(1, int(special_max_damage * get_special_damage_multiplier() * charge_ratio * distance_factor))
# Fija el presupuesto al primer contacto: el retroceso posterior no cambia el dano total.
var total_damage: int = int(_special_damage_budgets[target_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(target_id, 0))
if damage <= 0:
continue
_special_damage_dealt[target_id] = cumulative_damage
_applying_special_damage = true
target.call("take_damage", damage, global_position)
_applying_special_damage = false
## Atributos efectivos del intento; los raros pendientes no intervienen en estos valores.
func get_max_health() -> int:
return maxi(character_data.max_health + _permanent_max_health_bonus, 1) if character_data != null else 1
func get_basic_attack_damage() -> int:
if character_data == null:
return 0
return roundi(character_data.basic_attack_damage * (1.0 + _permanent_basic_damage_bonus) * (1.0 + _damage_boost_multiplier))
func get_special_damage_multiplier() -> float:
return 1.0 + _permanent_special_damage_bonus
## 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
match data.effect_type:
"heal":
var heal_amount: int = mini(int(data.value), get_max_health() - current_health)
if heal_amount <= 0:
return false
current_health += heal_amount
health_changed.emit(current_health, get_max_health())
_spawn_floating_text("+" + str(heal_amount), Color(0.2, 1.0, 0.3))
"speed_boost":
if data.value <= 0.0 or data.duration <= 0.0:
return false
_speed_boost_multiplier = max(_speed_boost_multiplier, data.value) if _speed_boost_timer > 0.0 else data.value
_speed_boost_timer = maxf(_speed_boost_timer, data.duration)
_spawn_floating_text("SPEED UP", Color(1.0, 0.8, 0.2))
"damage_boost":
# No se suman objetos: solo sustituye la potencia una mejora estrictamente superior.
if data.value <= _damage_boost_multiplier or data.value <= 0.0:
return false
_damage_boost_multiplier = data.value
_spawn_floating_text(data.display_name, data.color)
"air_damage_boost":
# Es un canal distinto del dano general; ambos siguen respetando el limite del pound.
if data.value <= _air_damage_boost_multiplier or data.value <= 0.0:
return false
_air_damage_boost_multiplier = data.value
_spawn_floating_text(data.display_name, data.color)
"damage_reduction", "jump_boost":
if data.value <= 0.0 or data.duration <= 0.0:
return false
# No acorta una mejora activa al recoger otro objeto con menos duracion.
if data.effect_type == "damage_reduction":
_damage_reduction_fraction = maxf(_damage_reduction_fraction, data.value) if _damage_reduction_timer > 0.0 else data.value
_damage_reduction_timer = maxf(_damage_reduction_timer, data.duration)
else:
_jump_boost_multiplier = maxf(_jump_boost_multiplier, data.value) if _jump_boost_timer > 0.0 else data.value
_jump_boost_timer = maxf(_jump_boost_timer, data.duration)
_spawn_floating_text(data.display_name, data.color)
"special_charge":
var new_charge: int = mini(special_max_charge, special_charge + int(data.value))
if new_charge <= special_charge:
return false
special_charge = new_charge
special_charge_changed.emit(special_charge, special_max_charge)
_spawn_floating_text("SPECIAL +" + str(int(data.value)), data.color)
"shield":
if data.value <= 0.0:
return false
_shield_hits = maxi(_shield_hits, int(data.value))
_spawn_floating_text("SHIELD", data.color)
_:
push_warning("Unknown pickup effect: %s" % data.effect_type)
return false
pickup_collected.emit(data)
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,
"timer": 1.2,
"pos": Vector2(-12, -60),
"color": color,
"velocity": Vector2(0, -25)
}
_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
entry.timer -= delta
_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"):
# 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 or (_applying_special_damage and not special_kills_grant_charge):
return
special_charge = min(special_charge + special_charge_per_kill, special_max_charge)
special_charge_changed.emit(special_charge, special_max_charge)
# ============================================================================
# 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, check_world: bool = false) -> void:
var target: Node = collider
# 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()
if target == null or not target.has_method("take_damage"):
return
var target_id: int = target.get_instance_id()
if hit_targets.has(target_id):
return
# El punetazo no puede atravesar paredes; un Ground Pound conserva su onda de area.
if check_world and target is Node2D:
var query := PhysicsRayQueryParameters2D.create(
global_position, (target as Node2D).global_position, WORLD_MASK, [get_rid()]
)
if not get_world_2d().direct_space_state.intersect_ray(query).is_empty():
return
hit_targets[target_id] = true
target.take_damage(damage, global_position)
## Ignora contactos no validos, retira mejoras ofensivas y resuelve escudo, vida y empuje.
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
# Un golpe aceptado rompe las mejoras ofensivas incluso si el escudo protege la vida.
# Los intentos sin dano, en invulnerabilidad o tras morir ya retornaron antes.
_damage_boost_multiplier = 0.0
_air_damage_boost_multiplier = 0.0
if _shield_hits > 0:
_shield_hits -= 1
invulnerability_timer = invulnerability_duration
_spawn_floating_text("BLOCK!", Color(0.7, 0.9, 1.0))
return
# 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
# 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
# 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)
_hurt_animation_timer = 0.18 * clampf(push_scale, 1.0, 1.5)
punch_timer = 0.0
ground_pound_active = false
COMBAT_FX.spawn(get_parent(), global_position, &"hit", knockback_direction)
feedback_camera.call("impact", 1.5 * clampf(push_scale, 0.8, 1.6), 0.18)
health_changed.emit(current_health, get_max_health())
if current_health == 0:
_die()
## Detiene el especial y comunica la derrota al LevelRoot (sin reinicio automatico).
func _die() -> void:
is_dead = true
_special_active = false
feedback_camera.call("start_solo", 0.0)
if animated_sprite.sprite_frames.has_animation(&"death"):
# El menu de derrota pausa la escena; solo este dibujo termina su caida.
animated_sprite.process_mode = Node.PROCESS_MODE_ALWAYS
animated_sprite.self_modulate = Color.WHITE
animated_sprite.speed_scale = 1.0
animated_sprite.play(&"death")
died.emit()
# La pantalla de derrota ofrece reiniciar, selector y titulo.
# ============================================================================
# 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)
_pound_landing_timer = maxf(0.0, _pound_landing_timer - delta)
punch_timer = max(punch_timer - delta, 0.0)
attack_cooldown_timer = max(attack_cooldown_timer - delta, 0.0)
ground_pound_cooldown_timer = maxf(0.0, ground_pound_cooldown_timer - delta)
ground_pound_debug_timer = max(ground_pound_debug_timer - delta, 0.0)
invulnerability_timer = max(invulnerability_timer - delta, 0.0)
if _speed_boost_timer > 0.0:
_speed_boost_timer = max(_speed_boost_timer - delta, 0.0)
else:
_speed_boost_multiplier = 0.0
# Cada mejora temporizada caduca por separado; nunca se muta el recurso de personaje.
_damage_reduction_timer = maxf(0.0, _damage_reduction_timer - delta)
_jump_boost_timer = maxf(0.0, _jump_boost_timer - delta)
if _damage_reduction_timer == 0.0:
_damage_reduction_fraction = 0.0
if _jump_boost_timer == 0.0:
_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 is_dead:
animation_name = &"death"
elif _special_active:
if _special_elapsed < special_duration * 0.15:
animation_name = &"special_start"
elif _special_elapsed > special_duration * 0.85:
animation_name = &"special_end"
else:
animation_name = &"special"
elif _hurt_animation_timer > 0.0:
animation_name = &"hurt"
elif ground_pound_active:
animation_name = &"ground_pound"
elif punch_timer > 0.0:
animation_name = &"punch"
elif not is_on_floor():
animation_name = &"jump" if velocity.y < 0.0 else &"fall"
elif _pound_landing_timer > 0.0:
animation_name = &"pound_land"
elif _landing_animation_timer > 0.0:
animation_name = &"land"
elif absf(velocity.x) > 10.0:
animation_name = &"walk"
# Cadencia proporcional al desplazamiento real, sin oscilacion artificial de piernas.
if animation_name == &"walk":
var pace: float = absf(velocity.x) / maxf(get_move_speed(), 1.0)
animated_sprite.speed_scale = lerpf(0.65, 1.55, clampf(pace, 0.0, 1.0))
else:
animated_sprite.speed_scale = 1.0
# 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():
# 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)
elif invulnerability_timer > 0.0 and int(invulnerability_timer * 12.0) % 2 == 0:
animated_sprite.self_modulate = Color(1.0, 1.0, 1.0, 0.55)
else:
animated_sprite.self_modulate = Color.WHITE
# ============================================================================
# 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
punch_collision.shape = punch_shape
punch_hitbox.collision_layer = 0
punch_hitbox.collision_mask = ENEMY_HURTBOX_MASK | BREAKABLE_HURTBOX_MASK
punch_hitbox.monitoring = true
var pound_shape: CircleShape2D = CircleShape2D.new()
pound_shape.radius = ground_pound_radius
ground_pound_collision.shape = pound_shape
ground_pound_hitbox.position = ground_pound_offset
ground_pound_hitbox.collision_layer = 0
ground_pound_hitbox.collision_mask = ENEMY_HURTBOX_MASK | BREAKABLE_HURTBOX_MASK
ground_pound_hitbox.monitoring = true
# ============================================================================
# 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))
# Los trazos dorados tipo baqueta pertenecen solo a Ivan.
if ground_pound_active and character_data != null and character_data.ground_pound_effect == "ground_pound":
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)
# 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:
var text_color: Color = entry.color
text_color.a = clampf(float(entry.timer) / 1.2, 0.0, 1.0)
draw_string(font, entry.pos, entry.text, HORIZONTAL_ALIGNMENT_LEFT, -1, 14, text_color)
if not show_debug_hitboxes:
return
# 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)
)
# El punetazo solo se dibuja mientras puede causar dano.
if punch_timer > 0.0:
_draw_rectangle_collision(
punch_collision,
Color(1.0, 0.05, 0.05, 0.25),
Color(1.0, 0.05, 0.05, 0.95),
punch_hitbox.position
)
# 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
draw_circle(
ground_pound_hitbox.position,
ground_pound_radius,
Color(1.0, 0.18, 0.05, pound_fill_alpha)
)
draw_arc(
ground_pound_hitbox.position,
ground_pound_radius,
0.0,
TAU,
48,
Color(1.0, 0.18, 0.05, pound_outline_alpha),
2.0
)
# 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:
fill_alpha = 0.12
outline_alpha = 0.6
var radius: float = clampf(special_radius, 1.0, 290.0)
draw_circle(Vector2.ZERO, radius, Color(1.0, 0.6, 0.05, fill_alpha))
draw_arc(Vector2.ZERO, radius, 0.0, TAU, 64,
Color(1.0, 0.6, 0.05, outline_alpha), 2.0)
## Convierte una forma rectangular local a un rectangulo de depuracion.
func _draw_rectangle_collision(
collision: CollisionShape2D,
fill_color: Color,
outline_color: Color,
extra_offset: Vector2 = Vector2.ZERO
) -> void:
var rectangle: RectangleShape2D = collision.shape as RectangleShape2D
if rectangle == null:
return
var center: Vector2 = collision.position + extra_offset
var rect: Rect2 = Rect2(center - rectangle.size / 2.0, rectangle.size)
draw_rect(rect, fill_color, true)
draw_rect(rect, outline_color, false, 2.0)