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

973 lines
34 KiB
GDScript

extends CharacterBody2D
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.
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
const ENEMY_HURTBOX_MASK: int = 1 << 4
const COMBAT_FX = preload("res://effects/combat_fx.gd")
# ============================================================================
# CHARACTER
# ============================================================================
@export_category("Character")
## Resource that identifies the selected band member and contains the stats
## that are allowed to differ between characters.
@export var character_data: CharacterData
# ============================================================================
# MOVEMENT
# ============================================================================
@export_category("Movement")
## Reaches full running speed quickly, but not instantly.
@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.
@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.
@export var turn_braking: float = 5800.0
## Air control stays responsive but weaker than movement on the floor.
@export var air_acceleration: float = 2000.0
# ============================================================================
# JUMP
# ============================================================================
@export_category("Jump")
## Allows a jump a few milliseconds after walking off a ledge.
@export var coyote_time: float = 0.17
## Remembers an early jump press just before landing.
@export var jump_buffer_time: float = 0.17
## Releasing jump while rising cuts the jump short.
@export_range(0.1, 1.0) var jump_cut_multiplier: float = 0.43
@export var gravity_multiplier: float = 1.0
@export var fall_gravity_multiplier: float = 1.6
@export var max_fall_speed: float = 1400.0
@export_category("Double Jump")
## Enables a second jump while in the air.
@export var enable_double_jump: bool = true
## Maximum number of jumps allowed (1 = only ground/coyote, 2 = double jump).
@export_range(1, 2, 1) var max_jumps: int = 2
## Height multiplier applied to the second jump relative to the character's jump force.
@export_range(0.5, 0.95, 0.01) var double_jump_multiplier: float = 0.8
# ============================================================================
# DAMAGE RECEIVED
# ============================================================================
@export_category("Damage received")
## Short grace period so a contact hitbox cannot drain all health in one frame.
@export var invulnerability_duration: float = 0.65
## Horizontal and vertical impulse applied when the player is hit.
@export var damage_knockback: Vector2 = Vector2(310.0, 270.0)
# ============================================================================
# PUNCH
# ============================================================================
@export_category("Punch")
@export var punch_duration: float = 0.28
@export var punch_windup: float = 0.055
@export var punch_active_duration: float = 0.11
@export var punch_cooldown: float = 0.34
@export var punch_hitbox_size: Vector2 = Vector2(28.0, 22.0)
@export var punch_offset: Vector2 = Vector2(28.0, -4.0)
# ============================================================================
# GROUND POUND
# ============================================================================
@export_category("Ground Pound")
## Minimum downward speed when the air attack starts.
@export var ground_pound_start_speed: float = 450.0
## Extra gravity while performing the air attack.
@export var ground_pound_gravity_multiplier: float = 4.5
## Small amount of steering kept during the fall.
@export_range(0.0, 1.0) var ground_pound_horizontal_control: float = 0.25
@export var ground_pound_radius: float = 54.0
@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.
@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
# ============================================================================
@export_category("Special Attack")
## Maximum charge of the special meter (0-100).
@export_range(0, 100, 1) var special_max_charge: int = 100
## Charge gained when an enemy dies.
@export_range(0, 100, 1) var special_charge_per_kill: int = 25
## Minimum charge required to use special attack.
@export_range(0, 100, 1) var special_min_use_charge: int = 25
## Maximum damage dealt by the special (at full charge, closest to player).
@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.
@export var special_radius: float = 100000.0
## Guitar draw, sustained solo, then recovery. Damage is shared by all pulses.
@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
# ============================================================================
@export_category("Debug")
## Draws the actual hurtbox and attack areas used by gameplay.
## Combat effects do not depend on this debug overlay.
@export var show_debug_hitboxes: bool = false
## Keeps the ground-pound area visible briefly after impact.
@export var debug_impact_duration: float = 0.18
# ============================================================================
# NODES
# ============================================================================
@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
# ============================================================================
# RUNTIME STATE
# ============================================================================
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_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
# Only runtime state changes: CharacterData remains immutable during pickups.
var _damage_boost_timer: float = 0.0
var _damage_boost_multiplier: float = 0.0
var _air_damage_boost_timer: 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 = []
# Tracks the highest point reached since leaving the ground, used to scale
# ground pound damage by jump height instead of fall distance.
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.
var punch_hit_targets: Dictionary = {}
var special_charge: int = 0
var _special_active: 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
var _punch_swing_shown: bool = false
func _ready() -> void:
if character_data == null:
push_error("Player needs a CharacterData resource.")
return
current_health = character_data.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, 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".
_connect_to_enemies()
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()
# Track the highest point reached since leaving the ground, so ground pound
# damage is based on jump height rather than the current fall distance.
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
# Landing is only reliable after move_and_slide() has resolved collisions.
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()
# ============================================================================
# MOVEMENT
# ============================================================================
func _handle_horizontal_movement(delta: float) -> void:
# Let impulses decay instead of immediately overwriting them with input.
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):
# 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.
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)
## Horizontal running speed with active pickups applied. Keeping the HUD and
## movement on the same calculation avoids showing a bonus that isn't used.
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)
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.
punch_hitbox.position = Vector2(
abs(punch_offset.x) * facing_direction,
punch_offset.y
)
# ============================================================================
# GRAVITY AND JUMP
# ============================================================================
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)
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)
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
# ============================================================================
# ATTACK INPUT
# ============================================================================
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"):
# The ground pound is an air attack: it only triggers while jumping or
# falling, so it never replaces a grounded punch.
if not is_on_floor():
_start_ground_pound()
return
if Input.is_action_just_pressed("special_attack"):
_start_special_attack()
return
# ============================================================================
# PUNCH
# ============================================================================
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()
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, roundi(character_data.basic_attack_damage * (1.0 + _damage_boost_multiplier)), punch_hit_targets)
# ============================================================================
# GROUND POUND
# ============================================================================
func _start_ground_pound() -> void:
if is_dead or _special_active or ground_pound_active:
return
punch_timer = 0.0
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.
velocity.y = max(velocity.y, ground_pound_start_speed)
func _ground_pound_impact() -> void:
ground_pound_active = false
ground_pound_debug_timer = debug_impact_duration
_landing_animation_timer = 0.20
COMBAT_FX.spawn(get_parent(), global_position + Vector2(0, 26),
&"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.
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 = {}
# 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.
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.
var query := PhysicsShapeQueryParameters2D.new()
query.shape = ground_pound_collision.shape
query.transform = ground_pound_collision.global_transform
query.collision_mask = ENEMY_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)
# ============================================================================
# SPECIAL ATTACK
# ============================================================================
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)
_spawn_floating_text("GUITAR SOLO!", Color(0.76, 0.85, 1.0))
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))
# Catch up when a long frame spans a pulse, without replaying previous pulses.
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
var effect_radius: float = minf(special_radius, 300.0) if special_radius > 0.0 else 300.0
COMBAT_FX.spawn(get_parent(), global_position, &"solo", facing_direction, effect_radius)
feedback_camera.call("impact", 2.0, 0.18, Color(0.61, 0.82, 1.0))
velocity.x = -facing_direction * 35.0
if _special_elapsed >= special_duration:
_special_active = false
_special_damage_budgets.clear()
_special_damage_dealt.clear()
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()
var max_distance: float = maxf(maxf(viewport_rect.size.x, viewport_rect.size.y) * 0.8, 1.0)
var pulse_count: int = maxi(special_pulse_count, 1)
for node: Node in get_tree().get_nodes_in_group("enemy"):
var enemy := node as Node2D
if enemy == null or not enemy.has_method("take_damage") or bool(enemy.get("is_dead")):
continue
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.
if not viewport_rect.grow(28.0).has_point(enemy.get_global_transform_with_canvas().origin):
continue
var enemy_id: int = enemy.get_instance_id()
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.
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))
if damage <= 0:
continue
_special_damage_dealt[enemy_id] = cumulative_damage
enemy.call("take_damage", damage, global_position)
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), character_data.max_health - current_health)
if heal_amount <= 0:
return false
current_health += heal_amount
health_changed.emit(current_health, character_data.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 = data.duration
_spawn_floating_text("SPEED UP", Color(1.0, 0.8, 0.2))
"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.
match data.effect_type:
"damage_boost":
_damage_boost_multiplier = max(_damage_boost_multiplier, data.value) if _damage_boost_timer > 0.0 else data.value
_damage_boost_timer = data.duration
"air_damage_boost":
_air_damage_boost_multiplier = max(_air_damage_boost_multiplier, data.value) if _air_damage_boost_timer > 0.0 else data.value
_air_damage_boost_timer = data.duration
"damage_reduction":
_damage_reduction_fraction = max(_damage_reduction_fraction, data.value) if _damage_reduction_timer > 0.0 else data.value
_damage_reduction_timer = data.duration
"jump_boost":
_jump_boost_multiplier = max(_jump_boost_multiplier, data.value) if _jump_boost_timer > 0.0 else data.value
_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
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)
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)
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.
enemy.connect(&"died", _on_enemy_died.bind(enemy))
func _on_enemy_died(_enemy: Node) -> void:
if is_dead:
return
special_charge = min(special_charge + special_charge_per_kill, special_max_charge)
special_charge_changed.emit(special_charge, special_max_charge)
# ============================================================================
# DEALING AND RECEIVING DAMAGE
# ============================================================================
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().
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
hit_targets[target_id] = true
target.take_damage(damage, global_position)
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
if _shield_hits > 0:
_shield_hits -= 1
invulnerability_timer = invulnerability_duration
_spawn_floating_text("BLOCK!", Color(0.7, 0.9, 1.0))
return
# At least one point of damage passes through an active reduction.
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.
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.
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, character_data.max_health)
if current_health == 0:
_die()
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.
call_deferred("_reload_level")
func _reload_level() -> void:
get_tree().reload_current_scene()
# ============================================================================
# TIMERS AND ANIMATION
# ============================================================================
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)
punch_timer = max(punch_timer - delta, 0.0)
attack_cooldown_timer = max(attack_cooldown_timer - delta, 0.0)
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
# Each effect expires independently; no mutation of the character resource.
_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)
_jump_boost_timer = maxf(0.0, _jump_boost_timer - delta)
if _damage_boost_timer == 0.0:
_damage_boost_multiplier = 0.0
if _air_damage_boost_timer == 0.0:
_air_damage_boost_multiplier = 0.0
if _damage_reduction_timer == 0.0:
_damage_reduction_fraction = 0.0
if _jump_boost_timer == 0.0:
_jump_boost_multiplier = 0.0
func _update_animation() -> void:
var animation_name: StringName = &"idle"
if _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 _landing_animation_timer > 0.0:
animation_name = &"land"
elif absf(velocity.x) > 10.0:
animation_name = &"walk"
# Custom CharacterData can still provide a smaller animation set.
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.
if animated_sprite.animation == animation_name and animated_sprite.frame > 0:
return
animated_sprite.play(animation_name)
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
# ============================================================================
# HITBOX SETUP
# ============================================================================
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
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
ground_pound_hitbox.monitoring = true
# ============================================================================
# DEBUG HITBOX DRAWING
# ============================================================================
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.
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
# Player hurtbox: always visible and deliberately subtle.
_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.
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
)
# Ground pound: show the real damage radius throughout the fall, then make
# it stronger for a few frames at the exact impact moment.
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
)
# Special: show full-screen effect indication. Brighter when fully charged.
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 viewport_rect: Rect2 = get_viewport().get_visible_rect()
var camera: Camera2D = get_viewport().get_camera_2d()
var screen_pos: Vector2 = Vector2.ZERO
if camera != null:
screen_pos = to_local(camera.get_screen_center_position())
draw_rect(
Rect2(screen_pos - viewport_rect.size * 0.5, viewport_rect.size),
Color(1.0, 0.6, 0.05, fill_alpha),
true
)
draw_rect(
Rect2(screen_pos - viewport_rect.size * 0.5, viewport_rect.size),
Color(1.0, 0.6, 0.05, outline_alpha),
false,
2.0
)
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)