diff --git a/README.md b/README.md index 46f26fb..458ae4d 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ del proyecto original. descubre automaticamente `levels/*.tscn`; no hay que registrar niveles. - **F6**: prueba directamente la escena de nivel que tengas abierta. - **Android**: los botones tactiles emiten las mismas acciones del `InputMap`. -- **Teclado**: A/D mover, W saltar/doble salto, J punetazo, K Ground Pound +- **Teclado**: A/D mover, S agacharse, S+W bajar una plataforma, W saltar/doble salto, J punetazo, K Ground Pound estando en el aire, L especial con carga, Escape/menu pausa o salida segun la pantalla de navegacion. @@ -185,7 +185,8 @@ Mas detalles en [guia de creacion](docs/guia_creacion_niveles.md) y |---|---| | `player/player.gd`, `player/player.tscn` | Reglas comunes, combate, radios, cooldowns | | `player/characters/*.tres` | Vida y estadisticas de los cuatro personajes | -| `ui/mobile_controls/mobile_controls.gd` | Entrada tactil e indicador de Ground Pound | +| `ui/mobile_controls/mobile_controls.gd` | Joystick flotante analogico, dedos independientes y liberacion de acciones | +| `ui/mobile_controls/touch_surface.gd` | Botones circulares, distribucion en abanico e indicador de Ground Pound | | `pickups/data/*.tres` | Curacion y otras potencias de consumibles | | `enemies/walker/walker.gd` | IA comun, dano, aturdimiento, persecucion y patrulla | | `enemies/variants/*.tscn` | Ajustes por enemigo colocable | diff --git a/docs/architecture.md b/docs/architecture.md index e749780..848943d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -112,6 +112,10 @@ Despues aparecen nodos y estado de partida. Las funciones estan documentadas: - Movimiento y salto: `_physics_process`, `_handle_horizontal_movement`, `_apply_gravity`, `_update_jump_windows`, `_handle_jump`, `get_move_speed`. +- Agachado y plataformas: `_update_crouch`, `_set_crouching`, `_can_stand_up`, + `_try_drop_through`, `_restore_platform_collisions`. Las formas del jugador + son propias de la instancia; las excepciones afectan solo a sus soportes + one-way actuales, nunca a la capa World completa. - Ataques: `_start_punch`, `_update_punch_damage`, `_start_ground_pound`, `_ground_pound_impact`, `_start_special_attack`, `_update_special_attack`, `_apply_special_attack`. @@ -135,6 +139,9 @@ de navegar. `_update_idle_behaviour`, `_move_towards`, `_try_jump` y `_find_jump_landing` resuelven una navegacion local, no rutas globales. Las fases ofensivas estan separadas en preparacion, barrido danino y recuperacion. +El punetazo alto comprueba el solapamiento de las formas actuales de ataque y +Hurtbox de Player (no el cache de Area2D del paso anterior). La postura agachada +reduce la zona vulnerable; no modifica el contrato de `take_damage` ni da inmunidad. `take_damage` aplica vida, empuje y aturdimiento; `_die` resuelve la muerte logica antes de su animacion. Los nodos derrotados se conservan porque los niveles usan sus estados y el numero total de encuentros. diff --git a/docs/characters.md b/docs/characters.md index 78a6b55..d9c7903 100644 --- a/docs/characters.md +++ b/docs/characters.md @@ -14,7 +14,7 @@ reglas de mejoras. No se suman impactos por dibujar mas rayos o platos. El especial conserva carga 100, +10 por baja, minimo 25, 2.4 s y cuatro pulsos. La Pua Perdida aplica su +20% igual a los cuatro; no cambia el formato de guardado. -Los cuatro recursos mantienen vida 50, velocidad 390, salto -600 y punetazo 5. +Los cuatro recursos mantienen vida 30, velocidad 250, salto -600 y punetazo 5. No se ha reajustado el movimiento, el dano enemigo ni el alcance especial de cada nivel. El radio especial de 00/01 sigue en 290; la plantilla conserva su valor heredado, una diferencia entre mapas, no entre personajes. diff --git a/docs/tuning.md b/docs/tuning.md index fe900e7..47c4108 100644 --- a/docs/tuning.md +++ b/docs/tuning.md @@ -27,7 +27,7 @@ player/characters/drummer.tres | `sprite_frames` | Animaciones del integrante | El recurso inicial de `player/player.tscn` es `guitarist.tres` (Diego), con -`move_speed = 390`, `jump_velocity = -600`, `max_health = 30` y dano base 5. +`move_speed = 250`, `jump_velocity = -600`, `max_health = 30` y dano base 5. Los cuatro perfiles tienen esos mismos valores. Cambiar uno solo romperia la regla de igualdad; las pruebas comprueban que no ocurre por accidente. Desde el menu se usa la eleccion de la tarjeta. Para probar con F6, selecciona @@ -47,6 +47,7 @@ sobrescrituras locales. No hace falta buscar una constante dentro del controlado | Categoria | Ajustes principales | |---|---| | Movement | Aceleracion, friccion, frenado al girar, control aereo | +| Crouch / Drop through | Altura de la caja agachado e impulso inicial de bajada | | Jump | Margen de borde, memoria de salto, corte al soltar, gravedad, caida maxima | | Double Jump | Activacion, numero de saltos y multiplicador del segundo impulso | | Damage received | Invulnerabilidad e impulso al recibir dano | @@ -86,6 +87,67 @@ El ajuste global `Feedback Strength = 0` sigue apagando sacudidas/superposicione La gravedad base permanece en los ajustes de fisica 2D del proyecto. No se ha creado un segundo valor global que la sustituya. +## Movimiento y controles de Android + +El perfil base de la banda pasa de 390 a 250 px/s (-36%). Los ajustes comunes +son aceleracion 1800, friccion 3200, frenado al girar 3800 y control aereo 1100. +Se conserva el impulso de salto, la gravedad, el zoom, el dano y los cooldowns. +La animacion de caminar llega al 100% de su cadencia en vez del 155%. +Comprueba la torre de Level01 y los saltos largos con el nuevo alcance horizontal. + +`ui/mobile_controls/mobile_controls.tscn` es la escena compartida por los niveles. +El joystick nace donde se apoya el primer dedo en la mitad izquierda, por debajo +del HUD; la zona muerta es 0.18 y se alcanza la maxima velocidad al 0.90 del +recorrido. Al levantar el dedo vuelve a reposo y el siguiente toque fija un centro +nuevo. `mobile_controls.gd` conserva un indice por dedo y libera las acciones al +pausar, perder foco, cambiar el tamano o salir del nivel. Los botones de accion +mantienen su dedo hasta soltarlo, incluso fuera del circulo (salto variable). + +`touch_surface.gd` dibuja el joystick y los cuatro botones circulares. `BUTTONS` +contiene los desplazamientos desde la esquina inferior derecha y sus radios, en +un viewport de referencia de 1280 x 720. El hit test usa la misma geometria, con +un margen tactil de 8 unidades y la zona segura de la pantalla. Salto y golpe +son los mas grandes y estan abajo; caer y solo quedan en un abanico escalonado +por encima. No se reutilizan las placas rectangulares de los menus. + +Para probarlo en el PC activa `show_on_desktop` en la instancia MobileControls +del nivel y ejecutalo con F6. El raton permite simular un dedo; el teclado sigue +siendo el de siempre. Para el multitouch real, utiliza un dispositivo Android. +La escena de los controles se puede previsualizar por separado en el editor. + +### Agacharse y atravesar plataformas + +Abajo en el joystick (o S en teclado) agacha en cualquier suelo. El umbral +vertical de entrada es `joystick_crouch_at = 0.55`; se mantiene hasta bajar de +`joystick_crouch_release_at = 0.35` o cambiar a una direccion horizontal. Arriba +no salta. Manteniendo abajo, un toque nuevo en Salto (S+W) permite descender +solo desde una pieza `TerrainPiece` con `one_way = true`. Sobre suelo solido +no inicia salto ni bajada. Mantener Salto no encadena descensos: hay que volver +a pulsar. Las plataformas inferiores siguen activas; las excepciones se retiran +cuando el cuerpo ha salido de las piezas atravesadas. La bajada consume el salto +de suelo, conservando el salto aereo si esta habilitado. + +La altura fisica y de la zona vulnerable se reduce al 62% (`crouch_height_ratio`) +sin mover los pies. Las cuatro animaciones `crouch` reutilizan la pose dibujada +`land_0`, sin estirar ni deformar el arte. Si no hay espacio libre arriba, el +jugador permanece agachado y puede salir lentamente al mover la direccion +horizontal tras soltar abajo. No se inician ataques en esa postura; los ya +iniciados y las reacciones al dano mantienen sus prioridades. `drop_through_speed` +vale 180 px/s y no se modifica la gravedad normal. + +Los punetazos altos de Walker conservan su alcance X y dano, pero su area mide +32x20 px y su centro esta 20 px sobre el origen. La reduccion de la zona vulnerable +permite esquivarlos a la misma altura. No hay invulnerabilidad por agacharse: los +ataques bajos, impactos que coincidan en altura y los ataques de jefe siguen +causando dano. El ajuste de una variante futura debe respetar la altura de su arte. + +Pruebas de integracion (despues de importar recursos): + +```bash +godot --headless --path . --script res://tests/test_crouch_runtime.gd +godot --headless --path . --script res://tests/test_mobile_controls_runtime.gd +``` + **Alcance independiente del zoom:** `special_radius` vale **290 unidades de mundo**, como maximo, tambien en `player/player.tscn` y en la plantilla. Level00/01/02 conservan sus sobrescrituras explicitas de 290. La formula de diff --git a/enemies/walker/walker.gd b/enemies/walker/walker.gd index b486ff6..a2ddd66 100644 --- a/enemies/walker/walker.gd +++ b/enemies/walker/walker.gd @@ -84,8 +84,9 @@ enum AttackState { ## Recuperacion tras el golpe antes de poder iniciar otro. @export var attack_recovery_duration: float = 0.30 -## Posicion inicial del area de ataque cuando el enemigo mira a la derecha. -@export var attack_start_offset: Vector2 = Vector2(34.0, 0.0) +## 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 @@ -676,24 +677,31 @@ func _reset_attack_hitbox_position() -> void: ## Aplica un solo impacto por objetivo y evita golpear a traves del escenario. func _update_attack_damage() -> void: - for area in attack_hitbox.get_overlapping_areas(): - var damage_target: Node = area.get_parent() - if damage_target == null or not damage_target.has_method("take_damage"): - continue - - var target_id: int = damage_target.get_instance_id() - if attack_hit_targets.has(target_id): - continue - - # El barrido no atraviesa paredes. El origen del empuje es el cuerpo enemigo, no su area adelantada. - var query := PhysicsRayQueryParameters2D.create( - global_position, (damage_target as Node2D).global_position, - collision_mask, [get_rid()] - ) - if not get_world_2d().direct_space_state.intersect_ray(query).is_empty(): - continue - attack_hit_targets[target_id] = true - damage_target.take_damage(attack_damage, global_position, attack_knockback_multiplier) + # 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. diff --git a/enemies/walker/walker.tscn b/enemies/walker/walker.tscn index e4131bc..9142730 100644 --- a/enemies/walker/walker.tscn +++ b/enemies/walker/walker.tscn @@ -7,7 +7,7 @@ size = Vector2(28, 52) [sub_resource type="RectangleShape2D" id="AttackShape"] -size = Vector2(32, 40) +size = Vector2(32, 20) [node name="Walker" type="CharacterBody2D" groups=["enemy"]] collision_layer = 4 diff --git a/player/character_data.gd b/player/character_data.gd index 0dda52d..73c9b2d 100644 --- a/player/character_data.gd +++ b/player/character_data.gd @@ -21,7 +21,7 @@ class_name CharacterData ## Vida maxima del integrante. Las mejoras temporales nunca modifican este recurso. @export_range(1, 100, 1) var max_health: int = 5 ## Velocidad horizontal base en pixeles por segundo. -@export var move_speed: float = 400.0 +@export var move_speed: float = 250.0 ## Impulso vertical inicial: mas negativo significa saltar mas alto. @export var jump_velocity: float = -600.0 ## Dano base de un punetazo. diff --git a/player/characters/animations/bassist_frames.tres b/player/characters/animations/bassist_frames.tres index d49b48b..4f048d3 100644 --- a/player/characters/animations/bassist_frames.tres +++ b/player/characters/animations/bassist_frames.tres @@ -214,6 +214,11 @@ filter_clip = true [resource] animations = [{ +"frames": [{"duration": 1.0, "texture": SubResource("land_0")}], +"loop": true, +"name": &"crouch", +"speed": 5.0 +}, { "frames": [{"duration": 1.0, "texture": SubResource("fall_0")}, {"duration": 1.0, "texture": SubResource("fall_1")}], "loop": true, "name": &"fall", diff --git a/player/characters/animations/drummer_frames.tres b/player/characters/animations/drummer_frames.tres index 82d3d8c..da0224b 100644 --- a/player/characters/animations/drummer_frames.tres +++ b/player/characters/animations/drummer_frames.tres @@ -214,6 +214,11 @@ filter_clip = true [resource] animations = [{ +"frames": [{"duration": 1.0, "texture": SubResource("land_0")}], +"loop": true, +"name": &"crouch", +"speed": 5.0 +}, { "frames": [{"duration": 1.0, "texture": SubResource("fall_0")}, {"duration": 1.0, "texture": SubResource("fall_1")}], "loop": true, "name": &"fall", diff --git a/player/characters/animations/guitarist_frames.tres b/player/characters/animations/guitarist_frames.tres index 584e8d8..96a197b 100644 --- a/player/characters/animations/guitarist_frames.tres +++ b/player/characters/animations/guitarist_frames.tres @@ -214,6 +214,11 @@ filter_clip = true [resource] animations = [{ +"frames": [{"duration": 1.0, "texture": SubResource("land_0")}], +"loop": true, +"name": &"crouch", +"speed": 5.0 +}, { "frames": [{"duration": 1.0, "texture": SubResource("fall_0")}, {"duration": 1.0, "texture": SubResource("fall_1")}], "loop": true, "name": &"fall", diff --git a/player/characters/animations/singer_frames.tres b/player/characters/animations/singer_frames.tres index 12741ee..63935b3 100644 --- a/player/characters/animations/singer_frames.tres +++ b/player/characters/animations/singer_frames.tres @@ -214,6 +214,11 @@ filter_clip = true [resource] animations = [{ +"frames": [{"duration": 1.0, "texture": SubResource("land_0")}], +"loop": true, +"name": &"crouch", +"speed": 5.0 +}, { "frames": [{"duration": 1.0, "texture": SubResource("fall_0")}, {"duration": 1.0, "texture": SubResource("fall_1")}], "loop": true, "name": &"fall", diff --git a/player/characters/bassist.tres b/player/characters/bassist.tres index 5ebfe09..ae877ab 100644 --- a/player/characters/bassist.tres +++ b/player/characters/bassist.tres @@ -10,7 +10,7 @@ display_name = "Fer" role_name = "BAJISTA" sprite_frames = ExtResource("2_frames") max_health = 30 -move_speed = 390.0 +move_speed = 250.0 jump_velocity = -600.0 basic_attack_damage = 5 air_attack_damage = 10 diff --git a/player/characters/drummer.tres b/player/characters/drummer.tres index 3aec091..734424c 100644 --- a/player/characters/drummer.tres +++ b/player/characters/drummer.tres @@ -10,7 +10,7 @@ display_name = "Ivan" role_name = "BATERIA" sprite_frames = ExtResource("2_frames") max_health = 30 -move_speed = 390.0 +move_speed = 250.0 jump_velocity = -600.0 basic_attack_damage = 5 air_attack_damage = 10 diff --git a/player/characters/guitarist.tres b/player/characters/guitarist.tres index 57f7296..38147af 100644 --- a/player/characters/guitarist.tres +++ b/player/characters/guitarist.tres @@ -10,7 +10,7 @@ display_name = "Diego" role_name = "GUITARRISTA" sprite_frames = ExtResource("2_frames") max_health = 30 -move_speed = 390.0 +move_speed = 250.0 jump_velocity = -600.0 basic_attack_damage = 5 air_attack_damage = 10 diff --git a/player/characters/singer.tres b/player/characters/singer.tres index 014c26e..4c0b9b2 100644 --- a/player/characters/singer.tres +++ b/player/characters/singer.tres @@ -10,7 +10,7 @@ display_name = "Hector" role_name = "CANTANTE" sprite_frames = ExtResource("2_frames") max_health = 30 -move_speed = 390.0 +move_speed = 250.0 jump_velocity = -600.0 basic_attack_damage = 5 air_attack_damage = 10 diff --git a/player/player.gd b/player/player.gd index a11dc0c..b3f4f76 100644 --- a/player/player.gd +++ b/player/player.gd @@ -39,7 +39,7 @@ const COMBAT_FX = preload("res://effects/combat_fx.gd") @export_category("Movement") ## Aceleracion horizontal en el suelo; no alcanza la velocidad maxima instantaneamente. -@export var ground_acceleration: float = 2000.0 +@export var ground_acceleration: float = 1800.0 ## Frenado al soltar la direccion. Mayor que la aceleracion para evitar deslizamiento. @export var ground_friction: float = 3200.0 @@ -51,6 +51,14 @@ const COMBAT_FX = preload("res://effects/combat_fx.gd") @export var air_acceleration: float = 1100.0 +@export_category("Crouch / Drop through") + +## Altura del cuerpo y de la zona vulnerable respecto a la altura de pie. +@export_range(0.4, 0.85, 0.01) var crouch_height_ratio: float = 0.62 +## Impulso inicial hacia abajo al atravesar una plataforma de un solo sentido. +@export_range(60.0, 400.0, 10.0) var drop_through_speed: float = 180.0 + + # ============================================================================ # SALTO # ============================================================================ @@ -201,6 +209,7 @@ const COMBAT_FX = preload("res://effects/combat_fx.gd") @onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D @onready var feedback_camera: Camera2D = $Camera2D +@onready var body_collision: CollisionShape2D = $CollisionShape2D @onready var hurtbox_collision: CollisionShape2D = $Hurtbox/CollisionShape2D @onready var punch_hitbox: Area2D = $PunchHitbox @onready var punch_collision: CollisionShape2D = $PunchHitbox/CollisionShape2D @@ -233,6 +242,15 @@ var ground_pound_debug_timer: float = 0.0 var is_dead: bool = false var jumps_remaining: int = 2 +var is_crouching: bool = false +var _standing_shape: RectangleShape2D +var _crouching_shape: RectangleShape2D +var _standing_body_position: Vector2 +var _standing_hurtbox_position: Vector2 +var _crouch_offset: Vector2 +var _headroom_shape: RectangleShape2D +## Excepciones SOLO de este jugador y de los soportes que decidio atravesar. +var _dropped_platforms: Array[TerrainPiece] = [] var _speed_boost_timer: float = 0.0 var _speed_boost_multiplier: float = 0.0 @@ -296,6 +314,7 @@ func _ready() -> void: jumps_remaining = max_jumps + _setup_crouch_shapes() _setup_attack_hitboxes() _update_facing() _update_animation() @@ -315,6 +334,7 @@ func _physics_process(delta: float) -> void: _update_timers(delta) _update_jump_windows(delta) + _update_crouch() _handle_attack_input() _handle_jump() _apply_gravity(delta) @@ -323,6 +343,8 @@ func _physics_process(delta: float) -> void: _update_floating_texts(delta) move_and_slide() + _restore_platform_collisions() + _update_crouch() # Registra el punto mas alto desde el despegue para calcular el dano por altura de salto. if not is_on_floor(): @@ -361,6 +383,13 @@ func _handle_horizontal_movement(delta: float) -> void: var braking: float = 110.0 if _special_active else 550.0 velocity.x = move_toward(velocity.x, 0.0, braking * delta) return + if is_crouching: + # Al soltar abajo bajo un techo, permite salir despacio sin quedar encerrado. + var crawl: float = 0.0 + if not Input.is_action_pressed(&"move_down"): + crawl = Input.get_axis(&"move_left", &"move_right") * get_move_speed() * 0.35 + velocity.x = move_toward(velocity.x, crawl, ground_friction * delta) + return var direction: float = Input.get_axis("move_left", "move_right") if direction != 0.0 and punch_timer <= 0.0: @@ -394,6 +423,121 @@ func _handle_horizontal_movement(delta: float) -> void: velocity.x = move_toward(velocity.x, target_speed, air_acceleration * delta) +# ============================================================================ +# AGACHARSE Y BAJAR PLATAFORMAS +# ============================================================================ + +## Dos formas propias por instancia; nunca se cambia el recurso compartido de la escena. +func _setup_crouch_shapes() -> void: + _standing_shape = body_collision.shape.duplicate() as RectangleShape2D + _crouching_shape = RectangleShape2D.new() + _crouching_shape.size = Vector2(_standing_shape.size.x, _standing_shape.size.y * crouch_height_ratio) + _standing_body_position = body_collision.position + _standing_hurtbox_position = hurtbox_collision.position + _crouch_offset = Vector2(0.0, (_standing_shape.size.y - _crouching_shape.size.y) * 0.5) + _headroom_shape = RectangleShape2D.new() + _headroom_shape.size = Vector2(_standing_shape.size.x, _crouch_offset.y * 2.0) + body_collision.shape = _standing_shape + hurtbox_collision.shape = _standing_shape + + +## Abajo solo agacha en suelo. No se cancelan ataques ya iniciados ni retrocesos. +func _update_crouch() -> void: + var wants_crouch: bool = is_on_floor() and Input.is_action_pressed(&"move_down") + wants_crouch = wants_crouch and not _special_active and not ground_pound_active + wants_crouch = wants_crouch and _hurt_animation_timer <= 0.0 and punch_timer <= 0.0 + if wants_crouch: + _set_crouching(true) + elif is_crouching and _can_stand_up(): + _set_crouching(false) + + +func _set_crouching(active: bool) -> void: + if is_crouching == active: + return + is_crouching = active + var shape: RectangleShape2D = _crouching_shape if active else _standing_shape + var offset: Vector2 = _crouch_offset if active else Vector2.ZERO + # El borde inferior no se mueve: ni saltito visual ni penetracion en el suelo. + body_collision.shape = shape + body_collision.position = _standing_body_position + offset + hurtbox_collision.shape = shape + hurtbox_collision.position = _standing_hurtbox_position + offset + + +## Comprueba solo el espacio que ocuparia la cabeza al levantarse, no el suelo. +func _can_stand_up() -> bool: + var query := PhysicsShapeQueryParameters2D.new() + query.shape = _headroom_shape + var head_position: Vector2 = _standing_body_position + Vector2(0.0, -_standing_shape.size.y * 0.5 + _crouch_offset.y) + query.transform = global_transform * Transform2D(0.0, head_position) + query.collision_mask = WORLD_MASK + query.exclude = [get_rid()] + query.collide_with_areas = false + query.collide_with_bodies = true + for hit: Dictionary in get_world_2d().direct_space_state.intersect_shape(query, 32): + var terrain := hit.get("collider") as TerrainPiece + # Una plataforma unidireccional no es un techo solido desde abajo. + if terrain == null or not terrain.one_way: + return false + return true + + +## Usa el soporte fisico actual, no una zona dibujada ni un temporizador global. +func _try_drop_through() -> bool: + if not is_on_floor() or not is_crouching: + return false + var added: Array[TerrainPiece] = [] + var contact := KinematicCollision2D.new() + var probe: Vector2 = -up_direction * maxf(floor_snap_length + 1.0, 2.0) + # test_move funciona tambien quieto, cuando el floor snap no deja slide collisions. + # Si dos plataformas comparten una junta, comprobar tambien el segundo soporte. + while test_move(global_transform, probe, contact, safe_margin): + var platform := contact.get_collider() as TerrainPiece + if ( + contact.get_normal().dot(up_direction) < cos(floor_max_angle) + or platform == null or not platform.collision_enabled or not platform.one_way + or added.has(platform) or _dropped_platforms.has(platform) + ): + # Un soporte solido sigue bloqueando; deshacer cualquier excepcion provisional. + for piece: TerrainPiece in added: + remove_collision_exception_with(piece) + return false + add_collision_exception_with(platform) + added.append(platform) + if added.is_empty(): + return false + _dropped_platforms.append_array(added) + # Consumir el salto de suelo impide que el coyote time o el buffer nos impulsen arriba. + jump_buffer_timer = 0.0 + coyote_timer = 0.0 + jumps_remaining = maxi(max_jumps - 1, 0) + velocity.y = drop_through_speed + if _can_stand_up(): + _set_crouching(false) + return true + + +## Recupera la colision cuando TODO el cuerpo de pie ha salido de esa pieza. +## No hay un plazo fijo que permita atravesar otra plataforma mas abajo. +func _restore_platform_collisions() -> void: + if _dropped_platforms.is_empty(): + return + var standing_bounds: Rect2 = (global_transform * Transform2D(0.0, _standing_body_position)) * Rect2(-_standing_shape.size * 0.5, _standing_shape.size) + for index: int in range(_dropped_platforms.size() - 1, -1, -1): + var platform: TerrainPiece = _dropped_platforms[index] + if not is_instance_valid(platform): + _dropped_platforms.remove_at(index) + continue + var bounds: Rect2 = platform.global_transform * Rect2(-platform.dimensions * 0.5, platform.dimensions) + if ( + not platform.collision_enabled or not platform.one_way + or not bounds.grow(platform.one_way_margin + safe_margin).intersects(standing_bounds, true) + ): + remove_collision_exception_with(platform) + _dropped_platforms.remove_at(index) + + ## Velocidad efectiva incluyendo mejoras. HUD y movimiento usan este mismo calculo. func get_move_speed() -> float: if character_data == null: @@ -452,6 +596,13 @@ func _update_jump_windows(delta: float) -> void: func _handle_jump() -> void: if _special_active or _hurt_animation_timer > 0.0: return + if is_crouching and jump_buffer_timer > 0.0: + # Abajo + salto es una orden distinta: si el soporte es solido no hace nada. + # Solo un toque nuevo en suelo puede bajar; no encadena caidas al mantener W. + jump_buffer_timer = 0.0 + if Input.is_action_just_pressed(&"jump") and Input.is_action_pressed(&"move_down"): + _try_drop_through() + return if ( jump_buffer_timer > 0.0 and not ground_pound_active @@ -476,7 +627,7 @@ func _handle_jump() -> void: ## 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: + if is_crouching or _special_active or _hurt_animation_timer > 0.0: return if Input.is_action_just_pressed("attack"): _start_punch() @@ -919,6 +1070,8 @@ func _update_animation() -> void: animation_name = &"ground_pound" elif punch_timer > 0.0: animation_name = &"punch" + elif is_crouching: + animation_name = &"crouch" elif not is_on_floor(): animation_name = &"jump" if velocity.y < 0.0 else &"fall" elif _pound_landing_timer > 0.0: @@ -931,7 +1084,7 @@ func _update_animation() -> void: # 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)) + animated_sprite.speed_scale = lerpf(0.65, 1.0, clampf(pace, 0.0, 1.0)) else: animated_sprite.speed_scale = 1.0 diff --git a/tests/test_band_resources.py b/tests/test_band_resources.py index 7197330..df1a672 100644 --- a/tests/test_band_resources.py +++ b/tests/test_band_resources.py @@ -29,9 +29,12 @@ class BandResourceTests(unittest.TestCase): def test_base_stats_remain_shared(self): for role in ROLES: data = source(f'player/characters/{role}.tres') - for stat in ('max_health = 30', 'move_speed = 390.0', 'jump_velocity = -600.0', 'basic_attack_damage = 5'): + for stat in ('max_health = 30', 'move_speed = 250.0', 'jump_velocity = -600.0', 'basic_attack_damage = 5'): self.assertIn(stat, data) + self.assertIn('move_speed: float = 250.0', source('player/character_data.gd')) player = source('player/player.gd') + self.assertIn('ground_acceleration: float = 1800.0', player) + self.assertIn('lerpf(0.65, 1.0, clampf(pace, 0.0, 1.0))', player) for stat in ('special_charge_per_kill: int = 10', 'special_min_use_charge: int = 25', 'special_max_damage: int = 30', 'special_pulse_count: int = 4', 'ground_pound_max_damage: int = 12'): diff --git a/tests/test_crouch_resources.py b/tests/test_crouch_resources.py new file mode 100644 index 0000000..e6a51e5 --- /dev/null +++ b/tests/test_crouch_resources.py @@ -0,0 +1,61 @@ +"""Geometry/resource contracts; runtime tests cover real physics and input.""" +from pathlib import Path +import re +import unittest + +ROOT = Path(__file__).resolve().parents[1] + + +def read(path): + return (ROOT / path).read_text(encoding='utf-8') + + +class CrouchResources(unittest.TestCase): + def test_high_punch_clears_crouch_but_not_standing(self): + player = read('player/player.gd') + walker = read('enemies/walker/walker.gd') + body_h = float(re.search(r'size = Vector2\(26, (\d+)\)', read('player/player.tscn'))[1]) + ratio = float(re.search(r'var crouch_height_ratio: float = ([\d.]+)', player)[1]) + attack_y = float(re.search(r'var attack_start_offset: Vector2 = Vector2\(34.0, (-?[\d.]+)\)', walker)[1]) + attack_h = float(re.search(r'size = Vector2\(32, (\d+)\)', read('enemies/walker/walker.tscn'))[1]) + feet = body_h / 2 + crouch_top = feet - body_h * ratio + attack_bottom = attack_y + attack_h / 2 + self.assertGreater(crouch_top, attack_bottom) + self.assertGreater(attack_bottom, -feet) + self.assertIn('attack_collision.shape.collide(', walker) + # Taking damage itself must not branch on the crouch state. + damage = player.split('func take_damage(', 1)[1].split('\nfunc ', 1)[0] + self.assertNotIn('is_crouching', damage) + + def test_all_four_reuse_real_crouched_pose(self): + for role in ('guitarist', 'drummer', 'bassist', 'singer'): + frames = read(f'player/characters/animations/{role}_frames.tres') + self.assertRegex(frames, r'"frames": \[\{"duration": 1\.0, "texture": SubResource\("land_0"\)\}\],\n"loop": true,\n"name": &"crouch"') + + def test_drop_excludes_only_actual_one_way_support(self): + player = read('player/player.gd') + drop = player.split('func _try_drop_through()', 1)[1].split('\nfunc ', 1)[0] + restore = player.split('func _restore_platform_collisions()', 1)[1].split('\nfunc ', 1)[0] + self.assertIn('test_move(global_transform', drop) + self.assertIn('not platform.one_way', drop) + self.assertIn('add_collision_exception_with(platform)', drop) + self.assertNotIn('collision_mask =', drop) + self.assertNotIn('set_collision_mask_value', drop) + self.assertIn('coyote_timer = 0.0', drop) + self.assertIn('remove_collision_exception_with(platform)', restore) + self.assertIn('intersects(standing_bounds', restore) + self.assertIn('one_way = true', read('world/terrain/platform.tscn')) + self.assertNotIn('one_way = true', read('world/terrain/ground.tscn')) + + def test_down_input_already_exists_and_is_released(self): + mobile = read('ui/mobile_controls/mobile_controls.gd') + self.assertIn('move_down={', read('project.godot')) + self.assertIn('_set_direction(&"move_down", 1.0)', mobile) + self.assertIn('Input.action_release(_direction_action)', mobile) + self.assertIn('_set_direction(&"")', mobile) + self.assertIn('joystick_crouch_release_at', mobile) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_crouch_runtime.gd b/tests/test_crouch_runtime.gd new file mode 100644 index 0000000..ca629c6 --- /dev/null +++ b/tests/test_crouch_runtime.gd @@ -0,0 +1,146 @@ +extends SceneTree + +## godot --headless --path . --script res://tests/test_crouch_runtime.gd +const PLAYER_SCENE: PackedScene = preload("res://player/player.tscn") +const PLATFORM_SCENE: PackedScene = preload("res://world/terrain/platform.tscn") +const GROUND_SCENE: PackedScene = preload("res://world/terrain/ground.tscn") +const ENEMY_SCENE: PackedScene = preload("res://enemies/variants/roadie.tscn") +var _failures: int = 0 +var _world: Node2D +var _player: CharacterBody2D + + +func _initialize() -> void: + call_deferred("_run") + + +func _run() -> void: + preload("res://tests/runtime_test_profile.gd").prepare(self) + _world = Node2D.new() + root.add_child(_world) + current_scene = _world + var ground: TerrainPiece = _terrain(GROUND_SCENE, 360.0, 120.0) + var lower: TerrainPiece = _terrain(PLATFORM_SCENE, 235.0, 20.0) + var upper: TerrainPiece = _terrain(PLATFORM_SCENE, 125.0, 20.0) + _player = PLAYER_SCENE.instantiate() as CharacterBody2D + _player.position = Vector2(320.0, 65.0) + _world.add_child(_player) + var body: CollisionShape2D = _player.get_node("CollisionShape2D") as CollisionShape2D + var hurtbox: CollisionShape2D = _player.get_node("Hurtbox/CollisionShape2D") as CollisionShape2D + var sprite: AnimatedSprite2D = _player.get_node("AnimatedSprite2D") as AnimatedSprite2D + await _frames(45) + _check(_player.is_on_floor() and absf(_player.position.y - 99.0) < 2.0, "Land on upper platform normally") + var standing_bottom: float = body.position.y + (body.shape as RectangleShape2D).size.y * 0.5 + var standing_y: float = _player.position.y + Input.action_press(&"move_down") + await _frames(5) + _check(bool(_player.get("is_crouching")) and sprite.animation == &"crouch", "Down plays a held crouch pose") + _check(absf(_player.position.y - standing_y) < 2.0, "Crouch leaves feet on the ground") + _check((body.shape as RectangleShape2D).size.y < 52.0 and body.shape == hurtbox.shape, "Body and hurtbox shrink together") + _check(is_equal_approx(body.position.y + (body.shape as RectangleShape2D).size.y * 0.5, standing_bottom), "Crouch keeps bottom anchored") + _check(is_equal_approx(hurtbox.position.y + (hurtbox.shape as RectangleShape2D).size.y * 0.5, standing_bottom), "Hurtbox bottom anchored") + await _frames(20) + _check(_player.is_on_floor() and absf(_player.position.y - standing_y) < 2.0, "Down alone never drops") + + Input.action_press(&"jump") + await _frames(5) + _check(not _player.is_on_floor() and _player.position.y > standing_y, "Down + jump drops instead of jumping up") + _check(is_zero_approx(float(_player.get("coyote_timer"))) and int(_player.get("jumps_remaining")) == 1, "Drop consumes only the ground jump") + _check(_player.get_collision_exceptions().has(upper) and not _player.get_collision_exceptions().has(lower), "Only the actual upper support is ignored") + await _frames(70) + _check(_player.is_on_floor() and absf(_player.position.y - 209.0) < 2.0, "Lower platform catches the player even while jump is held") + _check(not _player.get_collision_exceptions().has(upper), "Upper collision restored after full clearance") + _check(_player.get_collision_exceptions().is_empty(), "No persistent collision exceptions") + Input.action_release(&"jump") + await _frames(3) + Input.action_press(&"jump") + await _frames(70) + _check(_player.is_on_floor() and absf(_player.position.y - 334.0) < 2.0, "A second press drops to solid ground") + _check(_player.get_collision_exceptions().is_empty() and not _player.get_collision_exceptions().has(ground), "Solid ground stays enabled") + Input.action_release(&"jump") + await _frames(3) + Input.action_press(&"jump") + await _frames(30) + _check(_player.is_on_floor() and absf(_player.position.y - 334.0) < 2.0 and bool(_player.get("is_crouching")), "Down + jump on solid ground neither jumps nor falls") + Input.action_release(&"jump") + Input.action_release(&"move_down") + await _frames(5) + _check(not bool(_player.get("is_crouching")) and is_equal_approx((body.shape as RectangleShape2D).size.y, 52.0), "Release restores standing shape") + Input.action_press(&"jump") + await _frames(10) + _check(not _player.is_on_floor() and _player.velocity.y < 0.0, "Normal jump still works") + await _frames(85) + Input.action_release(&"jump") + _check(_player.is_on_floor() and absf(_player.position.y - 209.0) < 2.0, "Can jump back onto previously ignored platform") + + # Verify a blocked stand-up with an actual low solid ceiling. + var ceiling: TerrainPiece = _terrain(GROUND_SCENE, 150.0, 35.0) + # Avoid starting inside the ceiling: crouch before moving it above the head. + ceiling.position.x = 1100.0 + Input.action_press(&"move_down") + await _frames(5) + ceiling.position.x = _player.position.x + await _frames(3) + Input.action_release(&"move_down") + await _frames(5) + _check(bool(_player.get("is_crouching")), "A solid ceiling prevents expansion into geometry") + ceiling.queue_free() + await _frames(5) + _check(not bool(_player.get("is_crouching")), "Stands after headroom is clear") + + # Freeze actors on the same floor: verify current shape, not cached Area2D overlaps. + _player.set_physics_process(false) + _player.position = Vector2(320.0, 334.0) + _player.velocity = Vector2.ZERO + var enemy: CharacterBody2D = ENEMY_SCENE.instantiate() as CharacterBody2D + enemy.position = Vector2(270.0, 334.0) + _world.add_child(enemy) + enemy.set_physics_process(false) + enemy.set("attack_direction", 1.0) + enemy.call("_set_attack_hitbox_progress", 0.5) + await _frames(3) + var health: int = int(_player.get("current_health")) + var damage: int = int(enemy.get("attack_damage")) + _player.call("_set_crouching", true) + enemy.call("_update_attack_damage") + _check(int(_player.get("current_health")) == health and (enemy.get("attack_hit_targets") as Dictionary).is_empty(), "Crouch avoids a high punch immediately") + _player.call("_set_crouching", false) + enemy.call("_update_attack_damage") + _check(int(_player.get("current_health")) == health - damage, "Standing in the same high punch takes damage") + _player.set("invulnerability_timer", 0.0) + _player.set("_hurt_animation_timer", 0.0) + _player.call("_set_crouching", true) + enemy.set("attack_hit_targets", {}) + enemy.set("attack_start_offset", Vector2(34.0, 12.0)) + enemy.call("_set_attack_hitbox_progress", 0.5) + enemy.call("_update_attack_damage") + _check(int(_player.get("current_health")) == health - damage * 2, "A low hit still damages a crouched player") + _player.set("invulnerability_timer", 0.0) + _player.call("take_damage", 1, enemy.position) + _check(int(_player.get("current_health")) == health - damage * 2 - 1, "Crouch is not global invulnerability") + current_scene = null + _world.queue_free() + await process_frame + if _failures == 0: + print("OK CROUCH: shapes, down+jump, stacked platforms, headroom, high and low attacks") + quit(0 if _failures == 0 else 1) + + +func _terrain(scene: PackedScene, top: float, height: float) -> TerrainPiece: + var terrain: TerrainPiece = scene.instantiate() as TerrainPiece + terrain.dimensions = Vector2(260.0, height) + terrain.position = Vector2(320.0, top + height * 0.5) + _world.add_child(terrain) + return terrain + + +func _frames(count: int) -> void: + for _frame: int in range(count): + await physics_frame + await process_frame + + +func _check(condition: bool, message: String) -> void: + if not condition: + _failures += 1 + push_error(message) diff --git a/tests/test_enemy_ai_runtime.gd b/tests/test_enemy_ai_runtime.gd index 01b4cfd..74dce44 100644 --- a/tests/test_enemy_ai_runtime.gd +++ b/tests/test_enemy_ai_runtime.gd @@ -129,7 +129,7 @@ func _test_damage_and_push() -> void: _enemy.call("_set_attack_hitbox_progress", 0.5) await _frames(3) # El centro del barrido queda MAS ALLA del jugador. El empuje debe alejarlo - # del enemigo, no acercarlo. Se prueba el solapamiento real de Area2D. + # del enemigo, no acercarlo. Se prueba el solapamiento real de las formas de ataque y Hurtbox. _enemy.call("_update_attack_damage") _check(int(_player.get("current_health")) == 24, "Guard hit must deal six HP") _check(is_equal_approx(_player.velocity.x, 558.0), "Guard must push away with 1.8x horizontal impulse") diff --git a/tests/test_enemy_profiles.py b/tests/test_enemy_profiles.py index 8d88e77..af39f46 100644 --- a/tests/test_enemy_profiles.py +++ b/tests/test_enemy_profiles.py @@ -97,7 +97,7 @@ class EnemyProfileTests(unittest.TestCase): player = (ROOT / 'player/player.gd').read_text(encoding='utf-8') self.assertIn('knockback_multiplier: float = 1.0', player) enemy = (ROOT / 'enemies/walker/walker.gd').read_text(encoding='utf-8') - self.assertIn('take_damage(attack_damage, global_position, attack_knockback_multiplier)', enemy) + self.assertIn('target.call("take_damage", attack_damage, global_position, attack_knockback_multiplier)', enemy) if __name__ == '__main__': diff --git a/tests/test_mobile_controls_resources.py b/tests/test_mobile_controls_resources.py new file mode 100644 index 0000000..e07e009 --- /dev/null +++ b/tests/test_mobile_controls_resources.py @@ -0,0 +1,55 @@ +"""Contratos geometricos del overlay; la suite GDScript prueba los eventos reales.""" +from itertools import combinations +from math import hypot +from pathlib import Path +import re +import unittest + +ROOT = Path(__file__).resolve().parents[1] +SURFACE = (ROOT / 'ui/mobile_controls/touch_surface.gd').read_text(encoding='utf-8') + + +class MobileControlResources(unittest.TestCase): + def test_circular_action_layout_is_spaced_inside_safe_area(self): + buttons = { + name: (float(x), float(y), float(radius)) + for name, x, y, radius in re.findall( + r'&"(\w+)": \{"offset": Vector2\((\d+), (\d+)\), "radius": ([\d.]+)', + SURFACE, + ) + } + self.assertEqual(set(buttons), {'jump', 'attack', 'ground_pound', 'special_attack'}) + padding = float(re.search(r'HIT_PADDING: float = ([\d.]+)', SURFACE)[1]) + self.assertGreaterEqual(buttons['jump'][2], 75) + self.assertGreaterEqual(buttons['attack'][2], 75) + self.assertTrue(all(r > 56 for _, _, r in buttons.values())) + # Se prueba el layout a escala 1, en panoramica y con recortes laterales/inferiores. + for width, height in [(1280, 720), (1600, 720), (1504, 690), (1100, 600)]: + scale = min(1, width / 1280, height / 720) + for name, (x, y, radius) in buttons.items(): + hit = (radius + padding) * scale + cx, cy = width - x * scale, height - y * scale + self.assertGreater(cx - hit, width / 2, name) + self.assertLessEqual(cx + hit, width, name) + self.assertGreaterEqual(cy - hit, 0, name) + self.assertLessEqual(cy + hit, height, name) + for (a, (ax, ay, ar)), (b, (bx, by, br)) in combinations(buttons.items(), 2): + self.assertGreater(hypot(ax - bx, ay - by) * scale, + (ar + br + 2 * padding) * scale, (a, b)) + self.assertEqual(len({x for x, _, _ in buttons.values()}), 4) + self.assertEqual(len({y for _, y, _ in buttons.values()}), 4) + + def test_all_levels_keep_one_shared_overlay(self): + for name in ('level_00', 'level_01', 'level_02'): + text = (ROOT / f'levels/{name}.tscn').read_text(encoding='utf-8') + self.assertIn('res://ui/mobile_controls/mobile_controls.tscn', text) + self.assertEqual(text.count('[node name="MobileControls"'), 1) + scene = (ROOT / 'ui/mobile_controls/mobile_controls.tscn').read_text(encoding='utf-8') + self.assertIn('path="res://ui/mobile_controls/touch_surface.gd"', scene) + self.assertIn('mouse_filter = 2', scene) + self.assertNotIn('type="Button"', scene) + self.assertNotIn('button_plate.png', scene) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_mobile_controls_runtime.gd b/tests/test_mobile_controls_runtime.gd new file mode 100644 index 0000000..c085e86 --- /dev/null +++ b/tests/test_mobile_controls_runtime.gd @@ -0,0 +1,158 @@ +extends SceneTree + +## godot --headless --path . --script res://tests/test_mobile_controls_runtime.gd +const MOBILE_SCENE: PackedScene = preload("res://ui/mobile_controls/mobile_controls.tscn") +const MobileControls = preload("res://ui/mobile_controls/mobile_controls.gd") +const TouchSurface = preload("res://ui/mobile_controls/touch_surface.gd") +const ACTIONS: Array[StringName] = [&"jump", &"attack", &"ground_pound", &"special_attack"] +var _failures: int = 0 +var _mobile: MobileControls +var _surface: TouchSurface + + +func _initialize() -> void: + call_deferred("_run") + + +func _run() -> void: + preload("res://tests/runtime_test_profile.gd").prepare(self) + _mobile = MOBILE_SCENE.instantiate() as MobileControls + _mobile.show_on_desktop = true + root.add_child(_mobile) + await process_frame + _mobile.notification(Node.NOTIFICATION_APPLICATION_FOCUS_IN) + _surface = _mobile.get_node("Controls") as TouchSurface + for area: Rect2 in [Rect2(0, 0, 1280, 720), Rect2(0, 0, 1600, 720), Rect2(48, 0, 1504, 690)]: + _check_layout(area) + # Volvemos a las coordenadas reales del viewport para probar _input. + _mobile.call("_refresh_layout") + var move_area: Rect2 = _surface.movement_area() + var first: Vector2 = move_area.position + move_area.size * Vector2(0.40, 0.62) + var second: Vector2 = move_area.position + move_area.size * Vector2(0.67, 0.42) + var travel: float = _surface.joystick_travel() + var jump: Vector2 = _surface.button_center(&"jump") + var attack: Vector2 = _surface.button_center(&"attack") + var pound: Vector2 = _surface.button_center(&"ground_pound") + var solo: Vector2 = _surface.button_center(&"special_attack") + + # Primer toque donde cae el dedo, no sobre el joystick dibujado en reposo. + _touch(2, first, true) + _check(_mobile.direction_touch_index == 2, "El dedo izquierdo reserva el joystick") + _check(_surface._joystick_center.is_equal_approx(first), "El joystick nace en el toque") + _check(is_zero_approx(Input.get_axis(&"move_left", &"move_right")), "Tocar sin arrastrar no mueve") + _drag(2, first + Vector2(travel * 0.10, 0)) + _check(is_zero_approx(Input.get_axis(&"move_left", &"move_right")), "La zona muerta evita deriva") + _drag(2, first + Vector2(travel * 0.50, 0)) + var partial: float = Input.get_axis(&"move_left", &"move_right") + _check(partial > 0.0 and partial < 1.0, "El control es analogico") + _drag(2, first + Vector2(travel * 2.0, 0)) + _check(is_equal_approx(Input.get_axis(&"move_left", &"move_right"), 1.0), "El arrastre fuera del circulo sigue funcionando") + + _touch(5, jump, true) + _touch(8, attack, true) + _check(Input.is_action_pressed(&"jump") and Input.is_action_pressed(&"attack"), "Salto y ataque tienen dedos propios") + _check(Input.is_action_pressed(&"move_right"), "Los botones no interrumpen el movimiento") + _touch(9, jump, true) + _touch(9, jump, false) + _check(Input.is_action_pressed(&"jump"), "Un segundo dedo no roba el salto") + _drag(5, attack) + _check(Input.is_action_pressed(&"jump"), "Deslizar fuera mantiene el salto") + _touch(5, attack, false) + _check(not Input.is_action_pressed(&"jump") and Input.is_action_pressed(&"attack"), "Soltar salto no suelta ataque") + _touch(8, attack, false, true) + _check(not Input.is_action_pressed(&"attack"), "Un evento cancelado suelta su boton") + + # Abajo es una direccion propia y no se activa con una diagonal ligera. + _drag(2, first + Vector2(travel * 0.8, travel * 0.3)) + _check(Input.is_action_pressed(&"move_right") and not Input.is_action_pressed(&"move_down"), "Diagonal horizontal no agacha") + _drag(2, first + Vector2(0, travel * 0.50)) + _check(not Input.is_action_pressed(&"move_down"), "Umbral de agachado") + _drag(2, first + Vector2(0, travel * 0.75)) + _check(Input.is_action_pressed(&"move_down") and is_zero_approx(Input.get_axis(&"move_left", &"move_right")), "Abajo frena y agacha") + _drag(2, first + Vector2(0, travel * 0.45)) + _check(Input.is_action_pressed(&"move_down"), "Histeresis mantiene agachado") + _touch(5, jump, true) + _check(Input.is_action_pressed(&"jump") and Input.is_action_pressed(&"move_down"), "Abajo y salto tienen dedos independientes") + _touch(5, jump, false) + _drag(2, first + Vector2(0, travel * 0.20)) + _check(not Input.is_action_pressed(&"move_down"), "Volver al centro libera abajo") + _drag(2, first + Vector2(0, travel)) + _drag(2, first - Vector2(travel, 0)) + _check(not Input.is_action_pressed(&"move_down"), "Cambiar a izquierda libera abajo") + _check(Input.is_action_pressed(&"move_left") and not Input.is_action_pressed(&"move_right"), "Giro sin dos direcciones activas") + _drag(2, first) + _check(is_zero_approx(Input.get_axis(&"move_left", &"move_right")), "Volver al centro frena") + _touch(2, first, false) + _touch(3, second, true) + _check(_surface._joystick_center.is_equal_approx(second), "El siguiente toque recoloca el joystick") + _drag(3, second + Vector2(0, travel)) + _check(Input.is_action_pressed(&"move_down"), "El segundo origen permite agacharse") + _touch(10, pound, true) + _touch(11, solo, true) + _check(Input.is_action_pressed(&"ground_pound") and Input.is_action_pressed(&"special_attack"), "Caer y solo conservan sus acciones") + + paused = true + await process_frame + _mobile.call("_sync_visibility") + _check(not _surface.visible and _mobile.direction_touch_index == -1, "La pausa oculta y libera el joystick") + _check(not Input.is_action_pressed(&"move_left") and not Input.is_action_pressed(&"move_down") and not Input.is_action_pressed(&"ground_pound") and not Input.is_action_pressed(&"special_attack"), "Pausa no deja teclas tactiles atascadas") + paused = false + await process_frame + _mobile.call("_sync_visibility") + _drag(3, second + Vector2(travel, 0)) + _check(is_zero_approx(Input.get_axis(&"move_left", &"move_right")), "Reanudar requiere un toque nuevo") + _touch(4, first, true) + _drag(4, first + Vector2(0, travel)) + _touch(6, jump, true) + _mobile.notification(Node.NOTIFICATION_APPLICATION_FOCUS_OUT) + _check(not Input.is_action_pressed(&"jump") and not Input.is_action_pressed(&"move_down"), "Perder foco libera acciones y abajo") + _mobile.notification(Node.NOTIFICATION_APPLICATION_FOCUS_IN) + _touch(7, attack, true) + _check(Input.is_action_pressed(&"attack"), "Tras recuperar foco funcionan nuevos toques") + _mobile.queue_free() + await process_frame + await process_frame + _check(not Input.is_action_pressed(&"attack"), "Salir de la escena libera el boton") + if _failures == 0: + print("OK MOBILE: distribucion, joystick flotante analogico, multitouch, cancelacion, pausa y salida") + quit(0 if _failures == 0 else 1) + + +func _check_layout(area: Rect2) -> void: + _surface.set_safe_rect(area) + for action: StringName in ACTIONS: + var center: Vector2 = _surface.button_center(action) + var radius: float = _surface.button_radius(action) + var padding: float = TouchSurface.HIT_PADDING * _surface.layout_scale() + var extent := Vector2.ONE * (radius + padding) + _check(area.encloses(Rect2(center - extent, extent * 2.0)), "Boton dentro de zona segura: " + str(action)) + _check(center.x > area.get_center().x, "Acciones en la mitad derecha") + _check(_surface.action_at(center) == action, "Hit test en el centro") + _check(_surface.action_at(center + Vector2(radius * 0.88, radius * 0.88)) != action, "El hitbox es circular, no cuadrado") + for other: StringName in ACTIONS: + if other == action: + continue + _check(center.distance_to(_surface.button_center(other)) > radius + _surface.button_radius(other) + padding * 2.0, "No se superponen las areas tactiles") + _check(not _surface.movement_area().has_point(area.position + Vector2(20, 20)), "El HUD superior queda libre") + + +func _touch(index: int, local: Vector2, pressed: bool, canceled: bool = false) -> void: + var event := InputEventScreenTouch.new() + event.index = index + event.position = _surface.get_global_transform_with_canvas() * local + event.pressed = pressed + event.canceled = canceled + root.push_input(event, true) + + +func _drag(index: int, local: Vector2) -> void: + var event := InputEventScreenDrag.new() + event.index = index + event.position = _surface.get_global_transform_with_canvas() * local + root.push_input(event, true) + + +func _check(condition: bool, message: String) -> void: + if not condition: + _failures += 1 + push_error(message) diff --git a/ui/mobile_controls/mobile_controls.gd b/ui/mobile_controls/mobile_controls.gd index 50b3b63..ab31f00 100644 --- a/ui/mobile_controls/mobile_controls.gd +++ b/ui/mobile_controls/mobile_controls.gd @@ -1,110 +1,197 @@ extends CanvasLayer +## Adaptador tactil multitouch al InputMap existente. El dibujo no captura eventos. +const TouchSurface = preload("res://ui/mobile_controls/touch_surface.gd") +const MOUSE_FINGER: int = -2 -## La misma entrada del teclado, presentada como placas de metal tactiles. -## Se muestran en pantallas tactiles; el Inspector permite probarlas en escritorio. +## Permite probar con raton en escritorio sin modificar la configuracion del proyecto. @export var show_on_desktop: bool = false +## Fraccion del recorrido horizontal ignorada alrededor del centro. +@export_range(0.0, 0.45, 0.01) var joystick_deadzone: float = 0.18 +## Fraccion del recorrido a partir de la cual se alcanza la velocidad maxima. +@export_range(0.5, 1.0, 0.01) var joystick_full_speed_at: float = 0.90 +## Umbrales separados: la histeresis evita alternar agachado/de pie por un temblor. +@export_range(0.3, 0.9, 0.01) var joystick_crouch_at: float = 0.55 +@export_range(0.1, 0.8, 0.01) var joystick_crouch_release_at: float = 0.35 -@onready var move_left_button: Button = $Controls/MoveLeft -@onready var move_right_button: Button = $Controls/MoveRight -@onready var jump_button: Button = $Controls/Jump -@onready var attack_button: Button = $Controls/Attack -@onready var ground_pound_button: Button = $Controls/GroundPound -@onready var special_attack_button: Button = $Controls/SpecialAttack +@onready var controls: TouchSurface = $Controls var direction_touch_index: int = -1 +var _direction_action: StringName = &"" +var _origin: Vector2 +var _finger_actions: Dictionary = {} var _player: Node +var _touch_detected: bool = false +var _foreground: bool = true -## Asocia botones con las mismas acciones utilizadas por el teclado. func _ready() -> void: - $Controls.visible = show_on_desktop or DisplayServer.is_touchscreen_available() or OS.has_feature("mobile") - _bind_button(jump_button, &"jump") - _bind_button(attack_button, &"attack") - _bind_button(ground_pound_button, &"ground_pound") - _bind_button(special_attack_button, &"special_attack") + # Debe seguir procesando al pausar: libera los dedos antes de mostrar el menu. + process_mode = Node.PROCESS_MODE_ALWAYS + controls.resized.connect(_refresh_layout) + _refresh_layout() + _sync_visibility() -## Indica el enfriamiento del golpe aereo sin alterar la entrada del resto de botones. func _process(_delta: float) -> void: + _sync_visibility() + if not controls.visible: + return if not is_instance_valid(_player): _player = get_tree().get_first_node_in_group(&"player") - if not is_instance_valid(_player): - ground_pound_button.text = "CAER" - ground_pound_button.modulate = Color.WHITE - return - var remaining: float = float(_player.get("ground_pound_cooldown_timer")) - ground_pound_button.text = "CAER\n%ds" % ceili(remaining) if remaining > 0.0 else "CAER" - ground_pound_button.modulate = Color(0.55, 0.55, 0.55, 0.85) if remaining > 0.0 else Color.WHITE + var remaining: float = float(_player.get("ground_pound_cooldown_timer")) if is_instance_valid(_player) else 0.0 + controls.set_pound_seconds(ceili(maxf(remaining, 0.0))) + + +func _sync_visibility() -> void: + var enabled: bool = visible and _foreground and not get_tree().paused and ( + show_on_desktop or _touch_detected or DisplayServer.is_touchscreen_available() or OS.has_feature("mobile") + ) + if not enabled: + _release_all() + controls.visible = enabled + + +func _refresh_layout() -> void: + _release_all() + var area := Rect2(Vector2.ZERO, controls.size) + if OS.has_feature("mobile"): + var safe_screen := Rect2(DisplayServer.get_display_safe_area()) + if safe_screen.has_area(): + # La zona segura del SO esta en pixeles de pantalla; convertirla al mismo + # espacio logico que el dibujo y los eventos (incluye stretch/expand). + var to_screen: Transform2D = get_viewport().get_screen_transform() * controls.get_global_transform_with_canvas() + var safe_local: Rect2 = to_screen.affine_inverse() * safe_screen + var clipped: Rect2 = area.intersection(safe_local) + if clipped.has_area(): + area = clipped + controls.set_safe_rect(area) -## Mantiene un unico dedo para direccion y permite deslizarlo entre ambos lados. func _input(event: InputEvent) -> void: + if event is InputEventScreenTouch or event is InputEventScreenDrag: + _touch_detected = true + _sync_visibility() + if not controls.visible: + return + var handled: bool = false if event is InputEventScreenTouch: - $Controls.show() var touch := event as InputEventScreenTouch - if touch.pressed and direction_touch_index == -1: - var action := _direction_at(touch.position) - if action != &"": - direction_touch_index = touch.index - _press_direction(action) - elif not touch.pressed and touch.index == direction_touch_index: - _release_direction() + if touch.canceled or not touch.pressed: + handled = _release_touch(touch.index) + else: + handled = _begin_touch(touch.index, _local_point(touch.position)) elif event is InputEventScreenDrag: var drag := event as InputEventScreenDrag - if drag.index == direction_touch_index: - var action := _direction_at(drag.position) - if action != &"": - _press_direction(action) + handled = _drag_touch(drag.index, _local_point(drag.position)) + # El raton es solo una ayuda de escritorio. No duplicar el mouse sintetizado + # por Android, que se mantiene habilitado para los menus normales del juego. + elif show_on_desktop and event.device != InputEvent.DEVICE_ID_EMULATION: + if event is InputEventMouseButton: + var mouse_button := event as InputEventMouseButton + if mouse_button.button_index == MOUSE_BUTTON_LEFT: + if mouse_button.pressed: + handled = _begin_touch(MOUSE_FINGER, _local_point(mouse_button.position)) + else: + handled = _release_touch(MOUSE_FINGER) + elif event is InputEventMouseMotion: + var motion := event as InputEventMouseMotion + handled = _drag_touch(MOUSE_FINGER, _local_point(motion.position)) + if handled: + get_viewport().set_input_as_handled() + + +func _local_point(point: Vector2) -> Vector2: + return controls.get_global_transform_with_canvas().affine_inverse() * point + + +func _begin_touch(index: int, point: Vector2) -> bool: + if index == direction_touch_index or _finger_actions.has(index): + return true + var action: StringName = controls.action_at(point) + if action != &"": + # No se roba un boton ya pulsado por otro dedo ni se libera al soltar ese segundo dedo. + if not _finger_actions.values().has(action): + _finger_actions[index] = action + controls.set_action_pressed(action, true) + Input.action_press(action) + return true + if controls.movement_area().has_point(point): + if direction_touch_index == -1: + direction_touch_index = index + _origin = point + # El origen es EXACTAMENTE el primer toque, incluso lejos de la pista visual. + controls.set_joystick(_origin, Vector2.ZERO, true) + return true + return false + + +func _drag_touch(index: int, point: Vector2) -> bool: + if index == direction_touch_index: + var offset: Vector2 = (point - _origin).limit_length(controls.joystick_travel()) + controls.set_joystick(_origin, offset, true) + var axes: Vector2 = offset / maxf(controls.joystick_travel(), 1.0) + # Abajo debe predominar sobre el eje X; las diagonales poco profundas + # siguen sirviendo para correr. Solo se emite una direccion a la vez. + var threshold: float = joystick_crouch_at + if _direction_action == &"move_down": + threshold = minf(joystick_crouch_at, joystick_crouch_release_at) + if axes.y >= threshold and axes.y >= absf(axes.x): + _set_direction(&"move_down", 1.0) + return true + var horizontal: float = clampf(axes.x, -1.0, 1.0) + var strength: float = clampf(inverse_lerp(joystick_deadzone, joystick_full_speed_at, absf(horizontal)), 0.0, 1.0) + var action: StringName = &"" + if strength > 0.0: + action = &"move_left" if horizontal < 0.0 else &"move_right" + _set_direction(action, strength) + return true + # El boton inicial conserva el dedo aunque se deslice fuera; no se pierde un + # salto mantenido ni se ejecuta accidentalmente otra accion al cruzarla. + return _finger_actions.has(index) + + +func _set_direction(action: StringName, strength: float = 0.0) -> void: + if _direction_action != action and _direction_action != &"": + Input.action_release(_direction_action) + _direction_action = action + if action != &"": + Input.action_press(action, strength) + + +func _release_touch(index: int) -> bool: + if index == direction_touch_index: + _set_direction(&"") + direction_touch_index = -1 + controls.set_joystick(Vector2.ZERO, Vector2.ZERO, false) + return true + if _finger_actions.has(index): + var action: StringName = _finger_actions[index] + _finger_actions.erase(index) + Input.action_release(action) + controls.set_action_pressed(action, false) + return true + return false + + +func _release_all() -> void: + # Liberar SOLO las acciones activadas por esta instancia, sin un reset global. + if direction_touch_index != -1: + _release_touch(direction_touch_index) + for index: int in _finger_actions.keys(): + _release_touch(index) + + +func _notification(what: int) -> void: + if not is_node_ready(): + return + if what == NOTIFICATION_APPLICATION_FOCUS_OUT or what == NOTIFICATION_APPLICATION_PAUSED or what == NOTIFICATION_WM_WINDOW_FOCUS_OUT: + _foreground = false + _release_all() + elif what == NOTIFICATION_APPLICATION_FOCUS_IN or what == NOTIFICATION_APPLICATION_RESUMED or what == NOTIFICATION_WM_WINDOW_FOCUS_IN: + _foreground = true + _refresh_layout() -## Libera acciones al cambiar de escena para no dejar botones virtuales pulsados. func _exit_tree() -> void: - # Si la escena cambia mientras un dedo sigue apoyado, Godot puede no llegar - # a emitir button_up. Liberamos las acciones para no dejar una tecla virtual - # atascada al cargar la siguiente escena. - Input.action_release(&"move_left") - Input.action_release(&"move_right") - Input.action_release(&"jump") - Input.action_release(&"attack") - Input.action_release(&"ground_pound") - Input.action_release(&"special_attack") - - -## Determina que control horizontal contiene la posicion tactil. -func _direction_at(position: Vector2) -> StringName: - if move_left_button.get_global_rect().has_point(position): - return &"move_left" - if move_right_button.get_global_rect().has_point(position): - return &"move_right" - return &"" - - -## Activa una direccion y desactiva la opuesta. -func _press_direction(action: StringName) -> void: - var other_action: StringName = &"move_right" if action == &"move_left" else &"move_left" - Input.action_release(other_action) - Input.action_press(action) - - -## Suelta ambas direcciones y libera el dedo reservado. -func _release_direction() -> void: - Input.action_release(&"move_left") - Input.action_release(&"move_right") - direction_touch_index = -1 - - -## Conecta pulsacion y liberacion con la accion indicada. -func _bind_button(button: Button, action: StringName) -> void: - button.button_down.connect(_press_action.bind(action)) - button.button_up.connect(_release_action.bind(action)) - - -## Envia una pulsacion al InputMap compartido. -func _press_action(action: StringName) -> void: - Input.action_press(action) - - -## Libera la accion tactil en el InputMap compartido. -func _release_action(action: StringName) -> void: - Input.action_release(action) + _release_all() diff --git a/ui/mobile_controls/mobile_controls.tscn b/ui/mobile_controls/mobile_controls.tscn index 55dfb26..cc03925 100644 --- a/ui/mobile_controls/mobile_controls.tscn +++ b/ui/mobile_controls/mobile_controls.tscn @@ -1,35 +1,11 @@ -[gd_scene load_steps=7 format=3 uid="uid://g7h185yageqr"] +[gd_scene load_steps=4 format=3 uid="uid://g7h185yageqr"] [ext_resource type="Script" path="res://ui/editor_ui_visibility.gd" id="editor_ui_visibility"] [ext_resource type="Script" path="res://ui/mobile_controls/mobile_controls.gd" id="1_controls"] -[ext_resource type="Theme" path="res://ui/menu/menu_theme.tres" id="theme"] -[ext_resource type="Texture2D" path="res://assets/ashen/ui/button_plate.png" id="plate"] - -[sub_resource type="StyleBoxTexture" id="ButtonNormal"] -texture = ExtResource("plate") -texture_margin_left = 24.0 -texture_margin_top = 18.0 -texture_margin_right = 28.0 -texture_margin_bottom = 16.0 -content_margin_left = 12.0 -content_margin_top = 12.0 -content_margin_right = 12.0 -content_margin_bottom = 12.0 -modulate_color = Color(0.68, 0.61, 0.48, 0.78) - -[sub_resource type="StyleBoxTexture" id="ButtonPressed"] -texture = ExtResource("plate") -texture_margin_left = 24.0 -texture_margin_top = 18.0 -texture_margin_right = 28.0 -texture_margin_bottom = 16.0 -content_margin_left = 12.0 -content_margin_top = 14.0 -content_margin_right = 12.0 -content_margin_bottom = 10.0 -modulate_color = Color(1, 0.78, 0.51, 1) +[ext_resource type="Script" path="res://ui/mobile_controls/touch_surface.gd" id="2_surface"] [node name="MobileControls" type="CanvasLayer"] +process_mode = 3 layer = 100 script = ExtResource("1_controls") @@ -44,136 +20,4 @@ anchor_bottom = 1.0 grow_horizontal = 2 grow_vertical = 2 mouse_filter = 2 -theme = ExtResource("theme") - -[node name="MoveLeft" type="Button" parent="Controls"] -layout_mode = 1 -anchor_left = 0.0 -anchor_top = 1.0 -anchor_right = 0.0 -anchor_bottom = 1.0 -offset_left = 24.0 -offset_top = -140.0 -offset_right = 136.0 -offset_bottom = -28.0 -grow_horizontal = 1 -grow_vertical = 0 -focus_mode = 0 -theme_override_colors/font_color = Color(0.88, 0.82, 0.68, 0.92) -theme_override_colors/font_pressed_color = Color(1, 0.94, 0.77, 1) -theme_override_font_sizes/font_size = 32 -theme_override_styles/normal = SubResource("ButtonNormal") -theme_override_styles/pressed = SubResource("ButtonPressed") -theme_override_styles/hover = SubResource("ButtonNormal") -keep_pressed_outside = true -text = "<<" - -[node name="MoveRight" type="Button" parent="Controls"] -layout_mode = 1 -anchor_left = 0.0 -anchor_top = 1.0 -anchor_right = 0.0 -anchor_bottom = 1.0 -offset_left = 148.0 -offset_top = -140.0 -offset_right = 260.0 -offset_bottom = -28.0 -grow_horizontal = 1 -grow_vertical = 0 -focus_mode = 0 -theme_override_colors/font_color = Color(0.88, 0.82, 0.68, 0.92) -theme_override_colors/font_pressed_color = Color(1, 0.94, 0.77, 1) -theme_override_font_sizes/font_size = 32 -theme_override_styles/normal = SubResource("ButtonNormal") -theme_override_styles/pressed = SubResource("ButtonPressed") -theme_override_styles/hover = SubResource("ButtonNormal") -keep_pressed_outside = true -text = ">>" - -[node name="Jump" type="Button" parent="Controls"] -layout_mode = 1 -anchor_left = 1.0 -anchor_top = 1.0 -anchor_right = 1.0 -anchor_bottom = 1.0 -offset_left = -140.0 -offset_top = -264.0 -offset_right = -28.0 -offset_bottom = -152.0 -grow_horizontal = 0 -grow_vertical = 0 -focus_mode = 0 -theme_override_colors/font_color = Color(0.88, 0.82, 0.68, 0.92) -theme_override_colors/font_pressed_color = Color(1, 0.94, 0.77, 1) -theme_override_font_sizes/font_size = 16 -theme_override_styles/normal = SubResource("ButtonNormal") -theme_override_styles/pressed = SubResource("ButtonPressed") -theme_override_styles/hover = SubResource("ButtonNormal") -keep_pressed_outside = true -text = "SALTO" - -[node name="Attack" type="Button" parent="Controls"] -layout_mode = 1 -anchor_left = 1.0 -anchor_top = 1.0 -anchor_right = 1.0 -anchor_bottom = 1.0 -offset_left = -264.0 -offset_top = -140.0 -offset_right = -152.0 -offset_bottom = -28.0 -grow_horizontal = 0 -grow_vertical = 0 -focus_mode = 0 -theme_override_colors/font_color = Color(0.88, 0.82, 0.68, 0.92) -theme_override_colors/font_pressed_color = Color(1, 0.94, 0.77, 1) -theme_override_font_sizes/font_size = 16 -theme_override_styles/normal = SubResource("ButtonNormal") -theme_override_styles/pressed = SubResource("ButtonPressed") -theme_override_styles/hover = SubResource("ButtonNormal") -keep_pressed_outside = true -text = "ATAQUE" - -[node name="GroundPound" type="Button" parent="Controls"] -layout_mode = 1 -anchor_left = 1.0 -anchor_top = 1.0 -anchor_right = 1.0 -anchor_bottom = 1.0 -offset_left = -140.0 -offset_top = -140.0 -offset_right = -28.0 -offset_bottom = -28.0 -grow_horizontal = 0 -grow_vertical = 0 -focus_mode = 0 -theme_override_colors/font_color = Color(0.88, 0.82, 0.68, 0.92) -theme_override_colors/font_pressed_color = Color(1, 0.94, 0.77, 1) -theme_override_font_sizes/font_size = 16 -theme_override_styles/normal = SubResource("ButtonNormal") -theme_override_styles/pressed = SubResource("ButtonPressed") -theme_override_styles/hover = SubResource("ButtonNormal") -keep_pressed_outside = true -text = "CAER" - -[node name="SpecialAttack" type="Button" parent="Controls"] -layout_mode = 1 -anchor_left = 1.0 -anchor_top = 1.0 -anchor_right = 1.0 -anchor_bottom = 1.0 -offset_left = -264.0 -offset_top = -264.0 -offset_right = -152.0 -offset_bottom = -152.0 -grow_horizontal = 0 -grow_vertical = 0 -focus_mode = 0 -theme_override_colors/font_color = Color(0.88, 0.82, 0.68, 0.92) -theme_override_colors/font_pressed_color = Color(1, 0.94, 0.77, 1) -theme_override_font_sizes/font_size = 16 -theme_override_styles/normal = SubResource("ButtonNormal") -theme_override_styles/pressed = SubResource("ButtonPressed") -theme_override_styles/hover = SubResource("ButtonNormal") -keep_pressed_outside = true -text = "SOLO" +script = ExtResource("2_surface") diff --git a/ui/mobile_controls/touch_surface.gd b/ui/mobile_controls/touch_surface.gd new file mode 100644 index 0000000..4daf6a5 --- /dev/null +++ b/ui/mobile_controls/touch_surface.gd @@ -0,0 +1,187 @@ +@tool +extends Control + +## Presentacion y geometria compartida por el dibujo y el hit test. +## No lee Input ni ejecuta logica del jugador; tambien se puede ver en el editor. +const BUTTONS := { + &"jump": {"offset": Vector2(105, 110), "radius": 78.0, "label": "SALTO"}, + &"attack": {"offset": Vector2(285, 135), "radius": 76.0, "label": "GOLPE"}, + &"ground_pound": {"offset": Vector2(205, 280), "radius": 62.0, "label": "CAER"}, + &"special_attack": {"offset": Vector2(90, 360), "radius": 58.0, "label": "SOLO"}, +} +const BASE_SIZE := Vector2(1280, 720) +const GOLD := Color(0.91, 0.75, 0.48, 0.90) +const IVORY := Color(1.0, 0.92, 0.76, 0.96) +const BASE_JOYSTICK_RADIUS: float = 92.0 +const BASE_JOYSTICK_TRAVEL: float = 64.0 +const HIT_PADDING: float = 8.0 + +var _safe_rect: Rect2 +var _joystick_active: bool = false +var _joystick_center: Vector2 +var _joystick_offset: Vector2 +var _pressed: Dictionary = {} +var _pound_seconds: int = 0 + + +func _ready() -> void: + resized.connect(_on_resized) + _on_resized() + + +func _on_resized() -> void: + set_safe_rect(Rect2(Vector2.ZERO, size)) + + +func set_safe_rect(rect: Rect2) -> void: + _safe_rect = rect if rect.has_area() else Rect2(Vector2.ZERO, size) + queue_redraw() + + +func layout_scale() -> float: + # El viewport usa canvas_items/expand: las medidas se mantienen en 16:9 y 20:9. + # Si la zona segura es mas pequena, todo se reduce de forma proporcionada. + return maxf(0.1, minf(1.0, minf(_safe_rect.size.x / BASE_SIZE.x, _safe_rect.size.y / BASE_SIZE.y))) + + +func joystick_travel() -> float: + return BASE_JOYSTICK_TRAVEL * layout_scale() + + +func movement_area() -> Rect2: + # El tercio superior queda libre para el HUD. Toda la mitad izquierda inferior + # permite iniciar el joystick, no solo el circulo que sirve de pista visual. + return Rect2( + _safe_rect.position + Vector2(0.0, _safe_rect.size.y * 0.34), + Vector2(_safe_rect.size.x * 0.5, _safe_rect.size.y * 0.66) + ) + + +func button_center(action: StringName) -> Vector2: + var data: Dictionary = BUTTONS[action] + var offset: Vector2 = data["offset"] + return _safe_rect.end - offset * layout_scale() + + +func button_radius(action: StringName) -> float: + return float(BUTTONS[action]["radius"]) * layout_scale() + + +func action_at(point: Vector2) -> StringName: + if not _safe_rect.has_point(point): + return &"" + var closest: StringName = &"" + var best: float = INF + for action: StringName in BUTTONS: + var distance: float = point.distance_to(button_center(action)) + if distance <= button_radius(action) + HIT_PADDING * layout_scale() and distance < best: + closest = action + best = distance + return closest + + +func set_joystick(center: Vector2, offset: Vector2, active: bool) -> void: + _joystick_center = center + _joystick_offset = offset.limit_length(joystick_travel()) + _joystick_active = active + queue_redraw() + + +func set_action_pressed(action: StringName, pressed: bool) -> void: + if pressed: + _pressed[action] = true + else: + _pressed.erase(action) + queue_redraw() + + +func set_pound_seconds(seconds: int) -> void: + if _pound_seconds != seconds: + _pound_seconds = seconds + queue_redraw() + + +func _draw() -> void: + if not _safe_rect.has_area(): + return + _draw_joystick() + for action: StringName in BUTTONS: + _draw_action(action) + # No dejamos transformaciones pendientes en el CanvasItem. + draw_set_transform(Vector2.ZERO) + + +func _draw_joystick() -> void: + var factor: float = layout_scale() + var center: Vector2 = _joystick_center if _joystick_active else ( + _safe_rect.position + Vector2(144.0 * factor, _safe_rect.size.y - 138.0 * factor) + ) + var opacity: float = 1.0 if _joystick_active else 0.48 + draw_set_transform(center, 0.0, Vector2.ONE * factor) + draw_circle(Vector2.ZERO, BASE_JOYSTICK_RADIUS, Color(0.045, 0.034, 0.055, 0.54 * opacity), true, -1.0, true) + draw_arc(Vector2.ZERO, BASE_JOYSTICK_RADIUS - 2.0, 0.0, TAU, 96, Color(GOLD, GOLD.a * opacity), 3.0, true) + draw_arc(Vector2.ZERO, BASE_JOYSTICK_RADIUS - 11.0, 0.0, TAU, 96, Color(GOLD, 0.22 * opacity), 1.5, true) + # Izquierda/derecha para mover; abajo para agacharse y bajar plataformas. + for side: float in [-1.0, 1.0]: + var tip := Vector2(72.0 * side, 0.0) + draw_polyline(PackedVector2Array([tip + Vector2(-10.0 * side, -9.0), tip, tip + Vector2(-10.0 * side, 9.0)]), Color(IVORY, 0.65 * opacity), 3.0, true) + var down_tip := Vector2(0.0, 72.0) + draw_polyline(PackedVector2Array([down_tip + Vector2(-9.0, -10.0), down_tip, down_tip + Vector2(9.0, -10.0)]), Color(IVORY, 0.65 * opacity), 3.0, true) + var knob: Vector2 = _joystick_offset / factor if _joystick_active else Vector2.ZERO + draw_circle(knob + Vector2(0, 3), 34.0, Color(0.0, 0.0, 0.0, 0.30 * opacity), true, -1.0, true) + draw_circle(knob, 32.0, Color(0.37, 0.27, 0.20, 0.86 * opacity), true, -1.0, true) + draw_arc(knob, 30.0, 0.0, TAU, 64, Color(IVORY, 0.84 * opacity), 3.0, true) + draw_circle(knob, 6.0, Color(IVORY, 0.75 * opacity), true, -1.0, true) + + +func _draw_action(action: StringName) -> void: + var data: Dictionary = BUTTONS[action] + var radius: float = float(data["radius"]) + var pressed: bool = _pressed.has(action) + var cooling: bool = action == &"ground_pound" and _pound_seconds > 0 + var opacity: float = 0.52 if cooling else 1.0 + var rim: Color = IVORY if pressed else GOLD + var fill := Color(0.38, 0.24, 0.14, 0.86) if pressed else Color(0.055, 0.041, 0.060, 0.64) + draw_set_transform(button_center(action), 0.0, Vector2.ONE * layout_scale()) + draw_circle(Vector2(0, 3), radius, Color(0.0, 0.0, 0.0, 0.28 * opacity), true, -1.0, true) + draw_circle(Vector2.ZERO, radius - 1.0, Color(fill, fill.a * opacity), true, -1.0, true) + draw_arc(Vector2.ZERO, radius - 2.0, 0.0, TAU, 96, Color(rim, rim.a * opacity), 4.0 if pressed else 2.5, true) + draw_arc(Vector2.ZERO, radius - 10.0, 0.0, TAU, 96, Color(rim, 0.24 * opacity), 1.5, true) + # Iconos vectoriales: distinguibles sin tener que leer el texto durante el combate. + var ink := Color(IVORY, IVORY.a * opacity) + _draw_icon(action, Vector2(0.0, -12.0), radius / 78.0, ink) + var caption: String = "%ds" % _pound_seconds if cooling else str(data["label"]) + var font: Font = ThemeDB.fallback_font + var font_size: int = 18 if radius >= 70.0 else 16 + var text_width: float = font.get_string_size(caption, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).x + draw_string(font, Vector2(-text_width * 0.5, radius * 0.58), caption, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, ink) + + +func _draw_icon(action: StringName, origin: Vector2, factor: float, ink: Color) -> void: + # Los vertices estan en coordenadas de icono, no en las del viewport. + match action: + &"jump": + _stroke(origin, factor, [Vector2(0, 25), Vector2(0, -24)], ink) + _stroke(origin, factor, [Vector2(-19, -5), Vector2(0, -24), Vector2(19, -5)], ink) + &"attack": + # Puno cerrado, no una espada: corresponde al ataque real del personaje. + _stroke(origin, factor, [Vector2(-22, 7), Vector2(-22, -14), Vector2(-15, -24), Vector2(16, -24), Vector2(24, -14), Vector2(24, 6), Vector2(13, 23), Vector2(-12, 23), Vector2(-22, 7)], ink) + for x: float in [-10.0, 1.0, 12.0]: + _stroke(origin, factor, [Vector2(x, -23), Vector2(x, -5)], ink) + _stroke(origin, factor, [Vector2(-21, 4), Vector2(-8, -4), Vector2(10, -4), Vector2(13, 8), Vector2(-3, 12)], ink) + &"ground_pound": + _stroke(origin, factor, [Vector2(0, -26), Vector2(0, 12)], ink) + _stroke(origin, factor, [Vector2(-17, -4), Vector2(0, 13), Vector2(17, -4)], ink) + _stroke(origin, factor, [Vector2(-25, 25), Vector2(25, 25)], ink) + &"special_attack": + var points := PackedVector2Array() + for vertex: Vector2 in [Vector2(5, -30), Vector2(-22, 5), Vector2(-2, 5), Vector2(-9, 30), Vector2(24, -10), Vector2(3, -10)]: + points.append(origin + vertex * factor) + draw_colored_polygon(points, ink) + + +func _stroke(origin: Vector2, factor: float, vertices: Array, ink: Color) -> void: + var points := PackedVector2Array() + for vertex: Vector2 in vertices: + points.append(origin + vertex * factor) + draw_polyline(points, ink, 4.5 * factor, true)