extends CharacterBody2D ## Controlador comun de enemigos. Configura variantes en enemies/variants/*.tscn. ## Navegacion local y combate comparten estado; no dependen del codigo de los niveles. signal died # Las cinco variantes comparten controlador. Sus ajustes viven en enemies/variants; # no hace falta duplicar la IA ni crear una jerarquia por cada enemigo. const PLAYER_HURTBOX_MASK: int = 1 << 3 const DROP_MANAGER := preload("res://pickups/drop_manager.gd") const COMBAT_FX = preload("res://effects/combat_fx.gd") enum AttackState { IDLE, WINDUP, ACTIVE, RECOVERY, } # ============================================================================ # MOVIMIENTO # ============================================================================ @export_category("Movement") @export var move_speed: float = 78.0 @export var max_fall_speed: float = 800.0 ## Ver al enemigo lo activa; la proximidad inicia la persecucion. ## Una vez iniciada, continua hasta 1,5 veces esta distancia, sin exceder Chase Radius. @export_range(80.0, 1200.0, 10.0) var aggro_range: float = 340.0 ## Solo las variantes agiles saltan. Las demas se detienen ante paredes y bordes. @export var can_jump: bool = false @export_range(-900.0, -100.0, 10.0) var jump_velocity: float = -560.0 @export_range(0.2, 3.0, 0.05) var jump_cooldown: float = 0.9 ## Patrulla opcional alrededor del punto donde se coloco al enemigo en el editor. ## Cero deja al enemigo esperando hasta detectar al jugador. @export_range(0.0, 500.0, 5.0) var patrol_range: float = 0.0 @export_range(0.0, 4.0, 0.1) var patrol_pause: float = 0.8 ## El enemigo retrocede si el jugador se acerca demasiado mientras recarga el ataque. ## Cero lo desactiva (util para perseguidores cuerpo a cuerpo). @export_range(0.0, 250.0, 5.0) var preferred_distance: float = 0.0 ## Desnivel maximo aceptado para un aterrizaje; no salta a un vacio sin suelo detectado. @export_range(0.0, 400.0, 10.0) var max_jump_drop: float = 200.0 # ============================================================================ # COMBATE # ============================================================================ @export_category("Combat") @export_range(1, 100, 1) var max_health: int = 20 @export_range(0, 100, 1) var attack_damage: int = 1 ## Empuje aplicado al jugador, independiente del dano y del retroceso recibido por el enemigo. @export_range(0.0, 3.0, 0.05) var attack_knockback_multiplier: float = 1.0 ## Tiempo minimo entre el inicio de dos ataques. @export var attack_interval: float = 2.0 ## Distancia horizontal para preparar el ataque. Supera el area final ## para ofrecer tiempo de reaccion antes de que el golpe alcance al jugador. @export var attack_trigger_distance: float = 140.0 ## Evita iniciar ataques de suelo contra un jugador situado demasiado arriba o abajo. @export var attack_vertical_tolerance: float = 80.0 ## Preparacion visible anterior al impacto. La direccion queda fijada y permite esquivar por detras. @export var attack_windup_duration: float = 0.35 ## Duracion de la fase danina; el area de ataque avanza durante esta ventana. @export var attack_duration: float = 0.22 ## Recuperacion tras el golpe antes de poder iniciar otro. @export var attack_recovery_duration: float = 0.30 ## Posicion inicial del punetazo alto (a la altura de hombros). ## Una variante con ataque bajo puede ajustar Y y su forma sin dar inmunidad al agachado. @export var attack_start_offset: Vector2 = Vector2(34.0, -20.0) ## Distancia horizontal maxima que alcanza el barrido ofensivo. @export var attack_reach: float = 120.0 ## Interrupcion breve al recibir un golpe. Permite defenderse atacando durante la preparacion enemiga. @export var hit_stun_duration: float = 0.18 ## Impulso por punto de dano, dividido por la vida maxima: los enemigos resistentes retroceden menos. @export var knockback_strength: float = 400.0 ## Duracion del retroceso antes de que el frenado detenga al enemigo. @export var knockback_duration: float = 0.4 ## Umbral de dano que provoca un aturdimiento prolongado. @export_range(0, 100, 1) var stun_damage_threshold: int = 5 ## Duracion del aturdimiento cuando el impacto supera el umbral. @export var strong_hit_stun_duration: float = 0.7 ## Los impactos durante esta ventana siguen causando dano, pero no reinician aturdimiento ## ni interrumpen el barrido en preparacion. Evita bloquear enemigos a punetazos. @export_range(0.0, 3.0, 0.05) var stagger_resistance_duration: float = 0.95 # ============================================================================ # RECOMPENSAS Y REAPARICION # ============================================================================ @export_category("Drops") ## Tabla de recompensas aleatorias para encuentros normales. @export var drop_table: PickupDropTable ## Recompensa fija opcional: reemplaza a la tabla aleatoria, no se suma a ella. @export var guaranteed_drop: PickupData ## Permite que una prueba o regla externa gestione la recompensa sin duplicarla. ## Los niveles normales dejan que el enemigo gestione sus propios objetos. var drops_handled_by_level: bool = false @export_category("Respawn") ## Cero desactiva la reaparicion: un enemigo muerto permanece derrotado. @export var respawn_delay: float = 5.0 ## Duracion de lanzamiento, caida y desvanecimiento antes de ocultar el cuerpo. @export_range(0.3, 2.5, 0.05) var death_animation_duration: float = 0.9 ## Limite horizontal desde el origen; cero significa sin limite. ## Si pierde al jugador o supera este radio, vuelve a su posicion inicial. @export var chase_radius: float = 0.0 ## Nombre informativo para interfaces y pruebas de las variantes. @export var enemy_display_name: String = "Walker" # ============================================================================ # DEPURACION # ============================================================================ @export_category("Debug") ## Dibuja zonas vulnerables y areas de ataque. La anticipacion naranja ## es informacion de juego y permanece visible aunque esta opcion este desactivada. @export var show_debug_hitboxes: bool = false ## Barra de vida y numeros de dano para depuracion; no cambia la logica de combate. @export var show_debug_enemy_info: bool = true # ============================================================================ # NODOS # ============================================================================ @onready var body_collision: CollisionShape2D = $CollisionShape2D @onready var hurtbox_collision: CollisionShape2D = $Hurtbox/CollisionShape2D @onready var attack_hitbox: Area2D = $AttackHitbox @onready var attack_collision: CollisionShape2D = $AttackHitbox/CollisionShape2D @onready var floor_probe: RayCast2D = $FloorProbe @onready var visibility_notifier: VisibleOnScreenNotifier2D = $VisibleOnScreenNotifier2D @onready var visual: AnimatedSprite2D = $Visual # ============================================================================ # ESTADO DE LA PARTIDA # ============================================================================ var current_health: int var facing_direction: float = -1.0 var attack_state: int = AttackState.IDLE var attack_phase_timer: float = 0.0 var attack_cooldown_timer: float = 0.0 var attack_direction: float = -1.0 var hit_stun_timer: float = 0.0 var stagger_resistance_timer: float = 0.0 var is_awake: bool = false var is_dead: bool = false var spawn_position: Vector2 var target: Node2D var _is_pursuing: bool = false var _patrol_direction: float = 1.0 var _patrol_wait_timer: float = 0.0 var _jump_cooldown_timer: float = 0.0 var _jump_in_progress: bool = false var _jump_target_x: float = 0.0 ## Evita aplicar dano repetidamente al mismo objetivo durante un unico barrido. var attack_hit_targets: Dictionary = {} ## Tiempo restante del impulso de retroceso. var knockback_timer: float = 0.0 ## Numeros flotantes de dano. Cada entrada contiene texto, posicion local y tiempo restante. var _damage_texts: Array = [] var _hit_flash_timer: float = 0.0 var _death_elapsed: float = 0.0 var _last_hit_direction: float = 1.0 var _visual_position: Vector2 var _visual_scale: Vector2 var _visual_rotation: float var _visual_color: Color ## Captura el punto de origen, resuelve al jugador y configura fisica, recompensas y activacion. func _ready() -> void: _visual_position = visual.position _visual_scale = visual.scale _visual_rotation = visual.rotation _visual_color = visual.self_modulate spawn_position = global_position current_health = max_health target = get_tree().get_first_node_in_group(&"player") as Node2D attack_hitbox.collision_layer = 0 attack_hitbox.collision_mask = PLAYER_HURTBOX_MASK attack_hitbox.monitoring = true if drop_table == null: var default_table := load("res://enemies/walker/walker_drop.tres") if default_table != null: drop_table = default_table visibility_notifier.screen_entered.connect(_wake_up) _update_facing() _reset_attack_hitbox_position() visual.play(&"idle") queue_redraw() ## Prioriza muerte, inactividad, retroceso, ataque y navegacion en ese orden. func _physics_process(delta: float) -> void: if is_dead: _update_death_animation(delta) return _hit_flash_timer = maxf(0.0, _hit_flash_timer - delta) visual.self_modulate = Color(1.8, 1.8, 1.8) if _hit_flash_timer > 0.0 else _visual_color _update_timers(delta) _update_damage_texts(delta) _apply_gravity(delta) # Permanece inactivo hasta aparecer en pantalla una vez. # Tras activarse puede perseguir o regresar aunque vuelva a quedar fuera de camara. if not is_awake: velocity.x = 0.0 move_and_slide() _update_actor_animation() queue_redraw() return _acquire_target_if_needed() if target == null: velocity.x = 0.0 move_and_slide() _update_actor_animation() queue_redraw() return # Un impacto pausa movimiento y ataque. Primero aplica retroceso y luego frena. # La espera entre ataques sigue avanzando para que la interrupcion no reinicie un golpe inmediato. if hit_stun_timer > 0.0: if knockback_timer > 0.0: knockback_timer = max(knockback_timer - delta, 0.0) var fade: float = knockback_timer / knockback_duration if knockback_duration > 0.0 else 0.0 velocity.x = move_toward(velocity.x, 0.0, knockback_strength * delta * (1.0 - fade + 0.1)) else: velocity.x = move_toward(velocity.x, 0.0, knockback_strength * delta) move_and_slide() _update_actor_animation() queue_redraw() return if attack_state == AttackState.IDLE: _update_idle_behaviour(delta) else: _update_attack(delta) move_and_slide() _update_jump_visual() _update_actor_animation() queue_redraw() # ============================================================================ # ACTIVACION Y OBJETIVO # ============================================================================ ## Activa permanentemente al enemigo al entrar por primera vez en pantalla. func _wake_up() -> void: is_awake = true ## Recupera una referencia valida al jugador sin buscar mientras la actual sigue viva. func _acquire_target_if_needed() -> void: if target != null and is_instance_valid(target): return target = get_tree().get_first_node_in_group(&"player") as Node2D ## Orienta al enemigo hacia el objetivo si hay una diferencia horizontal significativa. func _face_target() -> void: var direction_to_target: float = signf(target.global_position.x - global_position.x) if direction_to_target == 0.0 or direction_to_target == facing_direction: return facing_direction = direction_to_target _update_facing() ## Sincroniza textura y sonda frontal; no altera la direccion de un ataque ya fijada. func _update_facing() -> void: # La sonda del borde sigue el movimiento. La direccion ofensiva se guarda aparte # para impedir que un ataque ya preparado gire siguiendo al jugador. floor_probe.position.x = abs(floor_probe.position.x) * facing_direction if attack_state == AttackState.IDLE: _reset_attack_hitbox_position() # Las variantes comparten caja de colision e IA, pero tienen texturas diferentes. visual.flip_h = facing_direction < 0.0 # ============================================================================ # MOVIMIENTO # ============================================================================ ## Aplica gravedad con limite de caida y sin acumular velocidad dentro del suelo. func _apply_gravity(delta: float) -> void: if is_on_floor(): return velocity += get_gravity() * delta velocity.y = min(velocity.y, max_fall_speed) ## Decide entre perseguir, volver al origen o esperar, respetando los radios configurados. func _update_idle_behaviour(delta: float) -> void: var offset_to_target: Vector2 = target.global_position - global_position var detection_distance: float = aggro_range * (1.5 if _is_pursuing else 1.0) var target_inside_leash: bool = ( chase_radius <= 0.0 or absf(target.global_position.x - spawn_position.x) <= chase_radius ) _is_pursuing = ( not bool(target.get("is_dead")) and target_inside_leash and offset_to_target.length_squared() <= detection_distance * detection_distance ) if _is_pursuing: _patrol_wait_timer = 0.0 _face_target() if attack_cooldown_timer <= 0.0 and _is_target_in_attack_trigger(): _start_attack() return # Un enemigo a distancia puede conservar espacio durante la recarga sin # atravesar paredes ni bordes: sigue usando la misma navegacion local. if preferred_distance > 0.0 and absf(offset_to_target.x) < preferred_distance \ and absf(offset_to_target.y) < attack_vertical_tolerance: var direction_away: float = -signf(offset_to_target.x) if direction_away == 0.0: direction_away = -facing_direction var retreat_x: float = global_position.x + direction_away * preferred_distance if chase_radius > 0.0: retreat_x = clampf(retreat_x, spawn_position.x - chase_radius, spawn_position.x + chase_radius) _move_towards(Vector2(retreat_x, global_position.y), delta) else: _move_towards(target.global_position, delta) elif patrol_range > 0.0 and absf(global_position.x - spawn_position.x) <= patrol_range + 24.0: _update_patrol(delta) else: # Cuando pierde al jugador fuera de su ronda, vuelve al lugar donde aparecio. _move_towards(spawn_position, delta) ## Ronda sencilla, con pausa en los extremos y sin saltos aleatorios. func _update_patrol(delta: float) -> void: if _patrol_wait_timer > 0.0: _patrol_wait_timer = maxf(0.0, _patrol_wait_timer - delta) velocity.x = 0.0 return var destination_x: float = spawn_position.x + _patrol_direction * patrol_range if absf(destination_x - global_position.x) <= 12.0: _patrol_direction *= -1.0 _patrol_wait_timer = patrol_pause velocity.x = 0.0 return _move_towards(Vector2(destination_x, spawn_position.y), delta) # Ante una pared o un borde sin aterrizaje, da la vuelta en lugar de quedarse bloqueado. if is_on_floor() and absf(velocity.x) < 0.01: _patrol_direction *= -1.0 _patrol_wait_timer = patrol_pause ## Navegacion local con deteccion de paredes, bordes y aterrizaje comprometido. func _move_towards(destination: Vector2, delta: float) -> void: # Mantiene el aterrizaje elegido durante el salto. Un impacto cancela ese objetivo para respetar el retroceso. if _jump_in_progress and not is_on_floor(): velocity.x = clampf((_jump_target_x - global_position.x) / delta, -move_speed, move_speed) return var offset: Vector2 = destination - global_position if absf(offset.x) > 8.0: facing_direction = signf(offset.x) _update_facing() if not is_on_floor(): velocity.x = move_toward(velocity.x, signf(offset.x) * move_speed, move_speed * 3.0 * delta) return var stopping_distance: float = 38.0 if _is_pursuing else 8.0 if absf(offset.x) <= stopping_distance and absf(offset.y) <= 36.0: velocity.x = 0.0 return # Actualiza la sonda tras girar: su resultado anterior miraba hacia el otro lado. # Se anticipa al borde para saltar antes de chocar con el escalon. floor_probe.force_raycast_update() var edge_ahead: bool = not floor_probe.is_colliding() var look_ahead: Vector2 = Vector2(facing_direction * maxf(32.0, move_speed * 0.25), 0.0) var wall_ahead: bool = test_move(global_transform, look_ahead) if _try_jump(destination, wall_ahead, edge_ahead): return if absf(offset.x) <= stopping_distance or edge_ahead: velocity.x = 0.0 return # Consulta frontal nueva, no is_on_wall() calculado con la direccion anterior. if test_move(global_transform, Vector2(facing_direction * 3.0, 0.0)): velocity.x = 0.0 return velocity.x = facing_direction * minf(move_speed, absf(offset.x) / delta) ## Comprueba capacidad, espera y aterrizaje antes de consumir un intento de salto. func _try_jump(destination: Vector2, wall_ahead: bool, edge_ahead: bool) -> bool: if not can_jump or not is_on_floor() or _jump_cooldown_timer > 0.0: return false var offset: Vector2 = destination - global_position var climb_needed: bool = offset.y < -36.0 if not wall_ahead and not edge_ahead and not climb_needed: return false # Tambien limita los intentos fallidos para no explorar el terreno en cada fotograma. _jump_cooldown_timer = 0.25 var gravity_y: float = get_gravity().y if gravity_y <= 0.0 or jump_velocity >= 0.0: return false var max_rise: float = jump_velocity * jump_velocity / (2.0 * gravity_y) - 10.0 if max_rise <= 0.0 or test_move(global_transform, Vector2(0.0, -max_rise)): return false var landing: Vector2 = _find_jump_landing(destination, max_rise, gravity_y, climb_needed) if not landing.is_finite(): return false _jump_target_x = landing.x _jump_in_progress = true _jump_cooldown_timer = jump_cooldown velocity = Vector2(facing_direction * move_speed, jump_velocity) COMBAT_FX.spawn(get_parent(), global_position + Vector2(0.0, 26.0), &"dust") return true ## Busca un suelo cercano alcanzable, con hueco para el cuerpo y tiempo de vuelo suficiente. func _find_jump_landing(destination: Vector2, max_rise: float, gravity_y: float, climbing: bool) -> Vector2: var body_shape: RectangleShape2D = body_collision.shape as RectangleShape2D var half_size: Vector2 = body_shape.size * 0.5 var feet_y: float = global_position.y + half_size.y var best_landing: Vector2 = Vector2.INF var best_score: float = INF var space: PhysicsDirectSpaceState2D = get_world_2d().direct_space_state # Explora unos pocos aterrizajes locales: deben caber ambos pies # y el tiempo de vuelo debe permitir cubrir la distancia horizontal. for distance: float in [48.0, 80.0, 120.0, 160.0, 200.0, 240.0]: var x: float = global_position.x + facing_direction * distance if chase_radius > 0.0 and absf(x - spawn_position.x) > chase_radius: continue var query := PhysicsRayQueryParameters2D.create( Vector2(x, feet_y - max_rise), Vector2(x, feet_y + max_jump_drop + 2.0), collision_mask, [get_rid()] ) var hit: Dictionary = space.intersect_ray(query) if hit.is_empty() or (hit["normal"] as Vector2).y > -0.7: continue var surface: Vector2 = hit["position"] if climbing and surface.y >= feet_y - 16.0: continue var flight_squared: float = jump_velocity * jump_velocity + 2.0 * gravity_y * (surface.y - feet_y) if flight_squared <= 0.0: continue var flight_time: float = (-jump_velocity + sqrt(flight_squared)) / gravity_y if distance > move_speed * flight_time * 0.9: continue var stable_landing: bool = true for side: float in [-1.0, 1.0]: var foot_x: float = x + side * (half_size.x + 3.0) query.from = Vector2(foot_x, surface.y - 4.0) query.to = Vector2(foot_x, surface.y + 4.0) var foot_hit: Dictionary = space.intersect_ray(query) if foot_hit.is_empty() or (foot_hit["normal"] as Vector2).y > -0.7: stable_landing = false break if not stable_landing: continue var landing: Vector2 = Vector2(x, surface.y - half_size.y - 2.0) var landing_transform: Transform2D = global_transform landing_transform.origin = landing if test_move(landing_transform, Vector2.UP * 2.0, null, 0.08, true): continue var score: float = landing.distance_squared_to(destination) if score < best_score: best_score = score best_landing = landing return best_landing ## Las piernas de los enemigos se animan segun velocidad y estado de la IA. ## Es puramente visual: ataque, hitboxes, navegacion y tiempos permanecen intactos. func _update_actor_animation() -> void: var animation: StringName = &"idle" if is_dead: animation = &"death" elif hit_stun_timer > 0.0: animation = &"hurt" elif attack_state != AttackState.IDLE: animation = &"attack" elif not is_on_floor(): animation = &"jump" elif absf(velocity.x) > 7.0: animation = &"walk" if visual.sprite_frames == null or not visual.sprite_frames.has_animation(animation): return visual.speed_scale = clampf(absf(velocity.x) / maxf(move_speed, 1.0), 0.7, 1.4) if animation == &"walk" else 1.0 if visual.animation != animation: visual.play(animation) ## Orienta ligeramente el sprite durante el vuelo sin cambiar su colision. func _update_jump_visual() -> void: if not _jump_in_progress: visual.scale = _visual_scale return if is_on_floor(): _jump_in_progress = false visual.scale = _visual_scale COMBAT_FX.spawn(get_parent(), global_position + Vector2(0.0, 26.0), &"dust") else: # La pose de salto ya esta dibujada; no deformar sus pixeles. visual.scale = _visual_scale # ============================================================================ # ATAQUE # ============================================================================ ## Comprueba distancia, altura y linea libre antes de permitir un ataque. func _is_target_in_attack_trigger() -> bool: var offset_to_target: Vector2 = target.global_position - global_position if ( not is_on_floor() or absf(offset_to_target.x) > attack_trigger_distance or absf(offset_to_target.y) > attack_vertical_tolerance ): return false # Una pared entre ambos exige navegar, no atacar a traves de ella. var query := PhysicsRayQueryParameters2D.create( global_position, target.global_position, collision_mask, [get_rid()] ) return get_world_2d().direct_space_state.intersect_ray(query).is_empty() ## Fija la direccion y entra en la fase de anticipacion. func _start_attack() -> void: # Fija la direccion al preparar el golpe; el jugador puede esquivar por detras sin que el area lo persiga. _face_target() attack_direction = facing_direction attack_state = AttackState.WINDUP attack_phase_timer = attack_windup_duration attack_cooldown_timer = attack_interval attack_hit_targets.clear() velocity.x = 0.0 _reset_attack_hitbox_position() ## Despacha la fase actual: preparacion, barrido danino o recuperacion. func _update_attack(delta: float) -> void: velocity.x = 0.0 match attack_state: AttackState.WINDUP: _update_attack_windup(delta) AttackState.ACTIVE: _update_active_attack(delta) AttackState.RECOVERY: _update_attack_recovery(delta) ## Espera el tiempo de anticipacion antes de activar el barrido. func _update_attack_windup(delta: float) -> void: attack_phase_timer = max(attack_phase_timer - delta, 0.0) if attack_phase_timer > 0.0: return attack_state = AttackState.ACTIVE attack_phase_timer = attack_duration _set_attack_hitbox_progress(0.0) ## Avanza el area danina y resuelve sus contactos. func _update_active_attack(delta: float) -> void: attack_phase_timer = max(attack_phase_timer - delta, 0.0) # Desplaza el area fisica desde cerca del cuerpo hasta su alcance maximo, dando margen para esquivar. var progress: float = 1.0 if attack_duration > 0.0: progress = 1.0 - (attack_phase_timer / attack_duration) _set_attack_hitbox_progress(clampf(progress, 0.0, 1.0)) _update_attack_damage() if attack_phase_timer > 0.0: return attack_state = AttackState.RECOVERY attack_phase_timer = attack_recovery_duration ## Finaliza la recuperacion y devuelve el control a la navegacion. func _update_attack_recovery(delta: float) -> void: attack_phase_timer = max(attack_phase_timer - delta, 0.0) if attack_phase_timer > 0.0: return attack_state = AttackState.IDLE attack_hit_targets.clear() _reset_attack_hitbox_position() ## Interpola el barrido entre su origen y su alcance, reflejado por la direccion fijada. func _set_attack_hitbox_progress(progress: float) -> void: var start_x: float = abs(attack_start_offset.x) var current_x: float = lerpf(start_x, attack_reach, progress) attack_hitbox.position = Vector2( current_x * attack_direction, attack_start_offset.y ) ## Devuelve el area ofensiva a su posicion inicial. func _reset_attack_hitbox_position() -> void: var direction: float = attack_direction if attack_state == AttackState.IDLE: direction = facing_direction attack_hitbox.position = Vector2( abs(attack_start_offset.x) * direction, attack_start_offset.y ) ## Aplica un solo impacto por objetivo y evita golpear a traves del escenario. func _update_attack_damage() -> void: # Solo hay un jugador por partida. Comprobar las formas con sus transformaciones # actuales evita usar un solapamiento de Area2D del fotograma fisico anterior. if not is_instance_valid(target) or not target.has_method("take_damage"): return var target_id: int = target.get_instance_id() if attack_hit_targets.has(target_id): return var area := target.get_node_or_null("Hurtbox") as Area2D if area == null or not area.monitorable or (area.collision_layer & PLAYER_HURTBOX_MASK) == 0: return var target_collision := area.get_node_or_null("CollisionShape2D") as CollisionShape2D if target_collision == null or target_collision.disabled or target_collision.shape == null: return if attack_collision.disabled or attack_collision.shape == null or not attack_collision.shape.collide( attack_collision.global_transform, target_collision.shape, target_collision.global_transform ): return # El barrido no atraviesa paredes. El empuje sigue saliendo del cuerpo enemigo. var query := PhysicsRayQueryParameters2D.create( global_position, target_collision.global_position, collision_mask, [get_rid()] ) if not get_world_2d().direct_space_state.intersect_ray(query).is_empty(): return attack_hit_targets[target_id] = true target.call("take_damage", attack_damage, global_position, attack_knockback_multiplier) ## Cancela el ataque y vacia su registro de impactos. func _interrupt_attack() -> void: if attack_state == AttackState.IDLE: return attack_state = AttackState.IDLE attack_phase_timer = 0.0 attack_hit_targets.clear() _reset_attack_hitbox_position() ## Descuenta los tiempos de ataque, salto, retroceso y aturdimiento. func _update_timers(delta: float) -> void: attack_cooldown_timer = max(attack_cooldown_timer - delta, 0.0) hit_stun_timer = max(hit_stun_timer - delta, 0.0) stagger_resistance_timer = maxf(0.0, stagger_resistance_timer - delta) _jump_cooldown_timer = maxf(_jump_cooldown_timer - delta, 0.0) # Los numeros de dano ascienden y pierden opacidad con el tiempo. ## Actualiza y elimina las entradas visuales de dano. func _update_damage_texts(delta: float) -> void: for i in range(_damage_texts.size() - 1, -1, -1): var entry: Dictionary = _damage_texts[i] entry.timer = max(entry.timer - delta, 0.0) entry.local_pos.y -= 40.0 * delta if entry.timer <= 0.0: _damage_texts.remove_at(i) # ============================================================================ # DANO Y REAPARICION # ============================================================================ ## Aplica vida, interrupcion, empuje y aturdimiento antes de comprobar muerte. func take_damage(amount: int, source_position: Vector2) -> void: if amount <= 0 or is_dead: return current_health = max(current_health - amount, 0) _hit_flash_timer = 0.09 is_awake = true _is_pursuing = true _last_hit_direction = signf(global_position.x - source_position.x) if _last_hit_direction == 0.0: _last_hit_direction = -facing_direction COMBAT_FX.spawn(get_parent(), global_position, &"hit", _last_hit_direction) var camera: Camera2D = get_viewport().get_camera_2d() if camera != null and camera.has_method("impact"): camera.call("impact", 1.0, 0.12) # Numero flotante de dano, exclusivamente visual. if show_debug_enemy_info: _damage_texts.append({ "text": str(amount), "local_pos": Vector2(0, -25), "timer": 1.0 }) if current_health == 0: _die() return # El primer impacto deja una ventana para atacar, pero los siguientes # no pueden reiniciar indefinidamente el aturdimiento ni cancelar el ataque. if stagger_resistance_timer > 0.0: return _interrupt_attack() _jump_in_progress = false visual.scale = _visual_scale # Los golpes mas fuertes empujan mas; la vida maxima amortigua ese retroceso. # La direccion siempre se aleja del origen del dano. var knockback_dir: float = signf(global_position.x - source_position.x) if knockback_dir == 0.0: knockback_dir = 1.0 var knockback_force: float = float(amount) * knockback_strength / float(max_health) velocity.x = knockback_dir * knockback_force velocity.y = -180.0 knockback_timer = knockback_duration # Un impacto normal causa una pausa breve; superar el umbral provoca aturdimiento prolongado. if amount >= stun_damage_threshold: hit_stun_timer = max(hit_stun_timer, strong_hit_stun_duration) else: hit_stun_timer = max(hit_stun_timer, hit_stun_duration) stagger_resistance_timer = maxf(stagger_resistance_duration, hit_stun_timer) var reaction_direction: float = signf(source_position.x - global_position.x) if reaction_direction != 0.0: facing_direction = reaction_direction _update_facing() ## Emite la muerte una vez y delega la recompensa segun el modo del nivel. func _die() -> void: if is_dead: return _interrupt_attack() is_dead = true _death_elapsed = 0.0 velocity = Vector2(_last_hit_direction * 150.0, -210.0) COMBAT_FX.spawn(get_parent(), global_position, &"death", _last_hit_direction) # La muerte logica y su senal ocurren una sola vez; la animacion no retrasa las recompensas. _update_actor_animation() died.emit() # Los encuentros de laboratorio entregan su objeto asignado; el resto conserva su tabla aleatoria. var drops: Array[PickupData] = [] if not drops_handled_by_level: if guaranteed_drop != null: drops.append(guaranteed_drop) elif drop_table != null: drops = DROP_MANAGER.roll_drop(drop_table) if not drops.is_empty(): var parent: Node = get_tree().current_scene if parent == null: parent = get_tree().root DROP_MANAGER.spawn_drops(drops, parent, global_position) # Desactiva el combate inmediatamente pero conserva la colision con World durante la caida # para evitar que el cuerpo atraviese el suelo en la animacion de muerte. hurtbox_collision.set_deferred("disabled", true) attack_collision.set_deferred("disabled", true) queue_redraw() ## Anima el cuerpo derrotado conservando el suelo y sin permitir nuevos ataques. func _update_death_animation(delta: float) -> void: _death_elapsed += delta _update_damage_texts(delta) var duration: float = maxf(death_animation_duration, 0.3) if _death_elapsed < duration: _apply_gravity(delta) velocity.x = move_toward(velocity.x, 0.0, 180.0 * delta) move_and_slide() # Los dos fotogramas dibujados incluyen la caida completa. Rotarlos # otra vez pondria el cadaver de pie y hundiria sus pies en el suelo. visual.rotation = _visual_rotation visual.position = _visual_position visual.scale = _visual_scale var fade: float = 1.0 - smoothstep(duration * 0.65, duration, _death_elapsed) var color: Color = Color(1.8, 1.8, 1.8) if _death_elapsed < 0.09 else _visual_color color.a = _visual_color.a * fade visual.self_modulate = color queue_redraw() return visible = false velocity = Vector2.ZERO body_collision.set_deferred("disabled", true) if respawn_delay <= 0.0: # Conserva el nodo muerto: el laboratorio lo consulta y el nivel 02 lo incluye en el total de enemigos. set_physics_process(false) elif _death_elapsed >= maxf(respawn_delay, duration): _respawn() ## Restaura el estado inicial y decide si debe estar activo al reaparecer. func _respawn() -> void: set_physics_process(true) _death_elapsed = 0.0 _hit_flash_timer = 0.0 _is_pursuing = false _patrol_direction = 1.0 _patrol_wait_timer = 0.0 _jump_in_progress = false _jump_cooldown_timer = 0.0 _jump_target_x = spawn_position.x visual.position = _visual_position visual.scale = _visual_scale visual.rotation = _visual_rotation visual.self_modulate = _visual_color _damage_texts.clear() global_position = spawn_position velocity = Vector2.ZERO current_health = max_health attack_state = AttackState.IDLE attack_phase_timer = 0.0 attack_cooldown_timer = 0.0 hit_stun_timer = 0.0 stagger_resistance_timer = 0.0 knockback_timer = 0.0 attack_hit_targets.clear() attack_direction = facing_direction _reset_attack_hitbox_position() body_collision.set_deferred("disabled", false) hurtbox_collision.set_deferred("disabled", false) attack_collision.set_deferred("disabled", false) visible = true is_dead = false # Si reaparece dentro de la camara se activa inmediatamente; de lo contrario espera al notificador. is_awake = visibility_notifier.is_on_screen() queue_redraw() # ============================================================================ # PRESENTACION Y DEPURACION DE COLISIONES # ============================================================================ ## Dibuja anticipacion ofensiva y elementos opcionales de depuracion. func _draw() -> void: if is_dead: if show_debug_enemy_info: _draw_damage_texts() return # Dibujo de reserva si no se ha podido importar la textura del enemigo. if visual.sprite_frames == null or not visual.sprite_frames.has_animation(visual.animation) \ or visual.sprite_frames.get_frame_count(visual.animation) == 0: _draw_rectangle_collision( body_collision, Color(0.18, 0.18, 0.20, 0.90), Color(0.85, 0.85, 0.90, 1.0) ) # Barra de vida y numeros flotantes de depuracion. if show_debug_enemy_info: _draw_enemy_health_bar() _draw_damage_texts() # La anticipacion naranja comunica un ataque real, no es una colision de depuracion. # Permanece visible tambien en Android sin las superposiciones rojas. if attack_state == AttackState.WINDUP: _draw_attack_telegraph() if not show_debug_hitboxes: return # Zona vulnerable a punetazos y golpes aereos. _draw_rectangle_collision( hurtbox_collision, Color(1.0, 0.05, 0.05, 0.12), Color(1.0, 0.05, 0.05, 0.55) ) # Area danina real del barrido, resaltada en rojo. if attack_state == AttackState.ACTIVE: _draw_rectangle_collision( attack_collision, Color(1.0, 0.05, 0.05, 0.28), Color(1.0, 0.05, 0.05, 0.95), attack_hitbox.position ) ## Anticipa visualmente el recorrido peligroso del siguiente barrido. func _draw_attack_telegraph() -> void: var rectangle: RectangleShape2D = attack_collision.shape as RectangleShape2D if rectangle == null: return var start_x: float = abs(attack_start_offset.x) * attack_direction var end_x: float = attack_reach * attack_direction var center_x: float = (start_x + end_x) * 0.5 var sweep_width: float = abs(end_x - start_x) + rectangle.size.x var center: Vector2 = Vector2(center_x, attack_start_offset.y) var sweep_size: Vector2 = Vector2(sweep_width, rectangle.size.y) var rect: Rect2 = Rect2(center - sweep_size / 2.0, sweep_size) draw_rect(rect, Color(1.0, 0.55, 0.05, 0.12), true) draw_rect(rect, Color(1.0, 0.55, 0.05, 0.85), false, 2.0) ## Dibuja una forma rectangular en las coordenadas locales del enemigo. 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) # Barra horizontal de vida situada sobre la cabeza. ## Representa la proporcion de vida restante sobre el enemigo. func _draw_enemy_health_bar() -> void: var bar_width: float = 40.0 var bar_height: float = 5.0 var bar_pos: Vector2 = Vector2(-bar_width * 0.5, -48.0) # Fondo de la barra. draw_rect(Rect2(bar_pos, Vector2(bar_width, bar_height)), Color(0.2, 0.2, 0.2, 0.8), true) # Relleno proporcional a la vida restante. var fill_ratio: float = float(current_health) / float(max_health) if max_health > 0 else 0.0 draw_rect( Rect2(bar_pos, Vector2(bar_width * fill_ratio, bar_height)), Color(0.85, 0.2, 0.2, 0.95), true ) # Borde de la barra. draw_rect(Rect2(bar_pos, Vector2(bar_width, bar_height)), Color(1, 1, 1, 0.6), false, 1.0) # Numeros de dano que ascienden y se desvanecen. ## Muestra numeros de dano con opacidad dependiente de su tiempo restante. func _draw_damage_texts() -> void: var font: Font = ThemeDB.get_default_theme().get_font("font", "Label") if font == null: return for entry in _damage_texts: var alpha: float = clamp(entry.timer, 0.0, 1.0) draw_string(font, entry.local_pos, entry.text, HORIZONTAL_ALIGNMENT_LEFT, -1, 16, Color(1, 1, 1, alpha))