TableTower/ui/touch_input.gd
RobinFiredrake 2fe9317b27 Phone layout and touch gestures
MobileLayout (Android, or --mobile to try it on a desktop): the List fills
the screen with a Spread/List swap; the bar drops the title, hint, zoom,
View, Help and Play/Build (the last three move into ☰); the tray hides its
Earlier column and shortens Roll again; DPI scaling. TouchInput (every
platform): a long press is a right-click, two fingers pan and pinch-zoom.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 18:58:33 -06:00

87 lines
2.2 KiB
GDScript

class_name TouchInput
extends Node
## Touch gestures for phones and tablets: a long press acts as a right-click
## (the same menus as on a desktop), and two fingers pan and pinch-zoom the
## spread. One finger still taps and drags as the mouse does (Godot turns
## touches into mouse events).
const HOLD := 0.5
const SLOP := 12.0
var m: Main
var _touches: Dictionary = {}
var _hold_at := Vector2.ZERO
var _hold_t := -1.0
var _pinch_dist := 0.0
var _pinch_mid := Vector2.ZERO
func _init(p_main: Main) -> void:
m = p_main
func _input(ev: InputEvent) -> void:
var t := ev as InputEventScreenTouch
if t:
if t.pressed:
_touches[t.index] = t.position
else:
_touches.erase(t.index)
_hold_t = 0.0 if t.pressed and _touches.size() == 1 else -1.0
_hold_at = t.position
if _touches.size() == 2:
_start_pinch()
return
var d := ev as InputEventScreenDrag
if d:
_touches[d.index] = d.position
if _hold_t >= 0.0 and d.position.distance_to(_hold_at) > SLOP:
_hold_t = -1.0
if _touches.size() == 2:
_pinch()
m.get_viewport().set_input_as_handled()
func _process(delta: float) -> void:
if _hold_t < 0.0:
return
_hold_t += delta
if _hold_t >= HOLD:
_hold_t = -1.0
right_click(_hold_at)
## Sends a right-click at a screen position, as a long press does.
static func right_click(at: Vector2) -> void:
var e := InputEventMouseButton.new()
e.button_index = MOUSE_BUTTON_RIGHT
e.pressed = true
e.position = at
e.global_position = at
Input.parse_input_event(e)
var up := e.duplicate() as InputEventMouseButton
up.pressed = false
Input.parse_input_event(up)
func _two() -> Array:
return _touches.values().slice(0, 2)
func _start_pinch() -> void:
var p := _two()
_pinch_dist = maxf(1.0, (p[0] as Vector2).distance_to(p[1]))
_pinch_mid = ((p[0] as Vector2) + (p[1] as Vector2)) / 2.0
_hold_t = -1.0
m.board.cancel_drag()
func _pinch() -> void:
var p := _two()
var dist := maxf(1.0, (p[0] as Vector2).distance_to(p[1]))
var mid := ((p[0] as Vector2) + (p[1] as Vector2)) / 2.0
var local := m.board.get_global_transform_with_canvas().affine_inverse() * mid
m.board.world.position += mid - _pinch_mid
m.board.set_zoom(m.board.zoom * dist / _pinch_dist, local)
_pinch_dist = dist
_pinch_mid = mid