Files
mortal-maze-the-game/ui/mobile_controls/mobile_controls.gd
T

198 lines
7.4 KiB
GDScript

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
## 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 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
func _ready() -> void:
# 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()
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")
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)
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:
var touch := event as InputEventScreenTouch
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
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()
func _exit_tree() -> void:
_release_all()