#38: touch action buttons

TouchButtons (phones only, Main adds it beside TouchSticks): Pause, Fear, Bomb,
Patch, Use (word from the new read-only Interactions.focus_info()) and Build,
round Sketch buttons that press the existing actions for at least one physics
tick, shown only when they can do something and hidden whenever the tree is
paused or a menu, panel or sign is up. Columns follow TouchSticks.move_on_right
(now a variable); both join "touch_controls" with apply_settings (Swap sticks),
which Main calls at startup; Prompts.move_side() reads the live sticks. Stick
fingers keep their drags over buttons. New Sketch icons: fear, patch, use,
build, pause. Test: game/tests/mobile/buttons_test.gd.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Forrest 2026-10-14 15:25:57 -04:00
parent 5392ae09af
commit e435b76aa2
9 changed files with 1115 additions and 48 deletions

View file

@ -5,7 +5,8 @@ extends Node3D
## Nothing here works in build mode.
## * Focus: the nearest gather point, workbench, or shed counter within its reach, preferring
## gather points with charges left over used-up ones; nearby points show their charges, the
## focused one its prompt (or why it can't be used).
## focused one its prompt (or why it can't be used). focus_info() says what interact would
## act on, read-only, for the phone's Use button (TouchButtons).
## * Gather: hold interact by day (D8) at a point with charges left and room in the pouch for
## the whole yield (so a charge is never half wasted).
## The scarecrow is rooted for gather_time looping the point's clip, then yield_amount goes
@ -53,6 +54,8 @@ const POPUP_TIME := 1.1
const POPUPS := 6
## Seconds a partner's press of interact waits (on the host) for its copy to reach a counter.
const PRESS_WINDOW := 0.3
## The phone's Use button's word for each kind of focus_info().
const FOCUS_LABELS := {"gather": "Gather", "repair": "Repair", "upgrade": "Upgrade", "workbench": "Workbench", "shed": "Shop"}
var config: GameConfig
var campaign: CampaignController
@ -162,6 +165,47 @@ func can_shoot() -> bool:
and not (shed_panel != null and shed_panel.is_open) and not (remote != null and remote.ui_open)
## What interact would act on now (the phone's Use button, TouchButtons; read-only, as of the
## last step): {} with nothing in reach (or in build mode, or down), else
## kind "gather", "repair", "upgrade", "workbench", or "shed": a channel under way or an
## open shop's menu, else (in step's order) a damaged structure in reach, a levelable
## one, the nearest point or counter
## label the button's word: Gather, Repair, Upgrade, Workbench, or Shop
## ready whether holding (or, at a counter, pressing) interact would do it now; false when
## it would be refused (the world label says why: nightfall, a full pouch, short of
## materials, max level, a broken workbench)
## progress 0-1 through the gather, repair, or upgrade under way; -1 when none is.
func focus_info() -> Dictionary:
if kit == null or not kit.alive or (build != null and build.active):
return {}
var day := campaign.is_daytime()
if gathering != null:
return _focus("gather", true, gather_elapsed / maxf(config.gather_time, 0.001))
if repairing >= 0:
return _focus("repair", true, repair_elapsed / maxf(config.repair_time, 0.001))
if upgrading >= 0:
return _focus("upgrade", true, upgrade_elapsed / maxf(config.structure_upgrade_time, 0.001))
if upgrade_panel != null and upgrade_panel.is_open:
return _focus("workbench", true)
if shed_panel != null and shed_panel.is_open:
return _focus("shed", true)
if structures != null and repair_target >= 0:
return _focus("repair", campaign.state.resources.can_afford(structures.repair_cost(repair_target), kit.slot))
if structures != null and upgrade_target >= 0:
return _focus("upgrade", day and structures.upgrade_blocker(upgrade_target, kit.slot) == "")
if focus is GatherNode:
return _focus("gather", _blocker(focus) == "")
if focus is Workbench:
return _focus("workbench", day and not (structures != null and structures.is_broken(structures.workbench_id())))
if focus is ShedCounter:
return _focus("shed", day)
return {}
func _focus(kind: String, ready: bool, progress: float = -1.0) -> Dictionary:
return {"kind": kind, "label": FOCUS_LABELS[kind], "ready": ready, "progress": clampf(progress, 0.0, 1.0) if progress >= 0.0 else -1.0}
## One physics tick, after the scarecrow kit.
func step(dt: float) -> void:
var held := remote.held(&"interact") if remote != null else Input.is_action_pressed("interact")

View file

@ -20,9 +20,10 @@ extends Node
## host's leaving ends the partner's game (back to this menu, which says why), the partner's
## leaving leaves the host alone. [M] mutes the microphone.
## * On a phone (MobilePort): no ToonLook (Main adds the ScreenLabels that draws the Label3Ds
## flat), no co-op, no Quit buttons, two thumbsticks (TouchSticks), and leaving the app
## pauses. Android's back button (go_back) closes what's on top or pauses, and quits from the
## main menu. The iOS test build adds PerfTest (frame times and test buttons).
## flat), no co-op, no Quit buttons, two thumbsticks (TouchSticks) and the action buttons
## (TouchButtons; their Pause pauses), both taking the settings (apply_settings), and leaving
## the app pauses. Android's back button (go_back) closes what's on top or pauses, and quits
## from the main menu. The iOS test build adds PerfTest (frame times and test buttons).
## Main processes while paused; the farm doesn't. Tests set save_path and settings_path
## before adding it to the tree.
@ -136,11 +137,19 @@ func _ready() -> void:
var hud_layer := farm.get_node_or_null("Hud")
if hud_layer != null:
hud_layer.add_child(coop_hud)
if MobilePort.active(): # the phone's thumbsticks, over the HUD (hidden with it in the menus)
if MobilePort.active(): # the phone's thumbsticks and buttons, over the HUD (hidden with it in the menus)
var sticks := TouchSticks.new()
sticks.name = "TouchSticks"
sticks.setup(sim)
hud_layer.add_child(sticks)
var buttons := TouchButtons.new()
buttons.name = "TouchButtons"
buttons.setup(sim)
buttons.blocked = func() -> bool: return screen != Screen.PLAYING
buttons.pause_requested.connect(pause)
hud_layer.add_child(buttons)
sticks.apply_settings(settings) # (settings.apply, above, ran before they were here)
buttons.apply_settings(settings)
if sim.audio != null:
sim.audio.wire_buttons($Menus)
_menu_camera = Camera3D.new()

View file

@ -30,10 +30,11 @@ static func touch() -> bool:
return MobilePort.active()
## The screen half the move stick is on: "right" or "left".
## #38 points this at TouchSticks' move_on_right variable (which #41's Swap setting flips).
## The screen half the move stick is on: "right" or "left", as the sticks in play have it
## (TouchSticks.move_on_right_now(): their move_on_right, which the Swap sticks setting flips;
## TouchSticks.MOVE_ON_RIGHT without them).
static func move_side() -> String:
return "right" if TouchSticks.MOVE_ON_RIGHT else "left"
return "right" if TouchSticks.move_on_right_now() else "left"
## The screen half the attack stick is on: the other one.

View file

@ -6,7 +6,8 @@ extends RefCounted
## sketched outlines (each edge drawn twice, slightly off, overshooting its corners), painted
## fills (a flat color, a lighter dab, a darker rim), and painted icons for the weapons, the
## materials, the backpack, the sun and moon, the scarecrow's portrait, what thieves take (crops,
## animals, supplies), the enemies, and the farmer and his wife (talking heads); and the morning
## animals, supplies), the enemies, the farmer and his wife (talking heads), and the phone's touch
## buttons (TouchButtons: fear, patch, use, build, pause; Bomb is the pumpkin bomb); and the morning
## screen's wooden sign (planks, a nailed sheet of paper, leaves). Every wobble comes from a hash of a seed, so a shape is drawn the
## same way each frame (no flicker).
## Icons are designed in a 100 x 100 box and scaled to the rect they're drawn in.
@ -39,7 +40,8 @@ const LEAF := Color(0.42, 0.64, 0.22)
## EnemySystem.TYPE_NAMES, and these.
const ICONS: Array[String] = ["pitchfork", "corn_shooter", "pumpkin_bomb", "potato_cannon", "shurikens",
"propane_torch", "alien_ray", "wood", "scrap", "straw", "alien_goop", "backpack", "sun", "moon", "portrait",
"crops", "animals", "supplies", "crow", "thief", "breaker", "ufo", "farmer", "farmers_wife"]
"crops", "animals", "supplies", "crow", "thief", "breaker", "ufo", "farmer", "farmers_wife",
"fear", "patch", "use", "build", "pause"]
static var _font: Font
@ -586,6 +588,54 @@ static func _icon(ci: CanvasItem, id: String) -> void:
for j in 5:
paint(ci, blob(flower + Vector2.from_angle(TAU * j / 5.0 - 0.3) * 5.5, 4.6, 4.6, 392.0 + j), Color(0.96, 0.42, 0.56), 397.0 + j, 1.2)
ci.draw_circle(flower, 3.4, Color(1.0, 0.84, 0.3))
"fear": # a fright: a jagged burst in the fear ring's blue, with a "boo" face
var blue := Color(0.36, 0.74, 1.0)
var burst := PackedVector2Array()
for i in 18:
var a := TAU * i / 18.0 - PI * 0.5
burst.append(Vector2(50, 50) + Vector2(cos(a), sin(a)) * (46.0 if i % 2 == 0 else 29.0) + jitter(403.0 + i, 1.8))
paint(ci, burst, blue, 422.0)
for k: float in [-1.0, 1.0]:
paint(ci, blob(Vector2(50.0 + 11.0 * k, 42.0), 5.5, 7.5, 423.0 + k), INK, 425.0 + k, 0.0)
paint(ci, blob(Vector2(50, 63), 8.5, 10.5, 427.0, 0.06), INK, 428.0, 0.0)
"patch": # a heart patched with a square of straw, stitched on
var heart := PackedVector2Array()
for i in 36:
var a := TAU * i / 36.0
var y := 13.0 * cos(a) - 5.0 * cos(2.0 * a) - 2.0 * cos(3.0 * a) - cos(4.0 * a)
heart.append(Vector2(50.0 + 40.0 * sin(a) * sin(a) * sin(a), 47.0 - 2.5 * y) + jitter(431.0 + i, 0.6))
paint(ci, heart, Color(0.88, 0.14, 0.12), 468.0)
var square := PackedVector2Array([Vector2(40, 37), Vector2(68, 33), Vector2(72, 61), Vector2(44, 65)])
paint(ci, square, Color(0.96, 0.82, 0.36), 469.0, 2.0)
for i in 4:
var a := square[i]
var b := square[(i + 1) % 4]
var across := (b - a).orthogonal().normalized() * 4.5
for k in 3:
var m := a.lerp(b, (k + 0.5) / 3.0)
ci.draw_line(m - across, m + across, INK, 2.5, true)
"use": # an open hand in a work glove, reaching out
var glove := Color(0.93, 0.79, 0.5)
for k in 4:
var x := 35.0 + k * 10.0
stroke(ci, Vector2(x, 58.0), Vector2(x + (k - 1.5) * 2.5, 20.0 + absf(k - 1.4) * 6.0), glove, 8.0, 471.0 + k)
stroke(ci, Vector2(34.0, 72.0), Vector2(16.0, 52.0), glove, 8.0, 475.0)
paint(ci, PackedVector2Array([Vector2(29, 50), Vector2(71, 49), Vector2(70, 82), Vector2(31, 83)]), glove, 476.0)
paint(ci, PackedVector2Array([Vector2(29, 80), Vector2(71, 79), Vector2(72, 95), Vector2(28, 96)]), glove.darkened(0.3), 477.0, 2.0)
"build": # a claw hammer
var grip := Vector2(28, 90)
var top := Vector2(60, 38)
stroke(ci, grip, top, WOOD, 10.0, 481.0)
var d := (top - grip).normalized() # along the handle
var p := d.orthogonal() # across it: the head, its striking face up and to the left
var c := top + d * 4.0
paint(ci, PackedVector2Array([c - p * 14.0 + d * 6.0, c - p * 30.0 + d * 1.0, c - p * 38.0 - d * 12.0, c - p * 28.0 - d * 6.0,
c - p * 14.0 - d * 6.0]), Color(0.56, 0.58, 0.62), 482.0, 2.0) # the claw, curling back
paint(ci, PackedVector2Array([c + p * 24.0 - d * 9.0, c + p * 24.0 + d * 9.0, c - p * 14.0 + d * 9.0, c - p * 14.0 - d * 9.0]),
Color(0.66, 0.68, 0.72), 483.0)
"pause": # two upright bars
for x: float in [25.0, 57.0]:
paint(ci, PackedVector2Array([Vector2(x, 17), Vector2(x + 18.0, 16), Vector2(x + 19.0, 84), Vector2(x + 1.0, 85)]), TEXT, 491.0 + x, 3.0)
## An open outline (pts) closed with straight edges through corners, in steps about 5 long, so

View file

@ -0,0 +1,429 @@
class_name TouchButtons
extends Control
## The phone's action buttons (MobilePort; Main adds them over the HUD, beside TouchSticks):
## round, hand-drawn (Sketch), an icon and at most one word each. They press the input actions
## the keys press (Input.action_press while the finger is down, held for at least one physics
## tick so a quick tap still counts), so the game reads them as it reads a key. Each shows only
## when it can do something:
## * Pause (top edge, beside the day widget): opens the pause menu, as Escape does
## (pause_requested; Main.pause). Shown while the game is being played (playing): not while
## the tree is paused (a conversation, the pause menu) or a shop menu, the pouch panel, the
## morning sign, or the end panel is up, which have their own buttons.
## * Fear: fear (a tap). Its ring is fear's recharge, as the portrait's; lit when ready.
## * Bomb: offhand (a tap throws a pumpkin bomb along the attack stick, or the way it last
## pointed, as on a gamepad). Once pumpkin bombs are owned; its ring is the recharge.
## * Patch: patch (hold), when hurt with the straw for it (the pouch or the shed); its ring is
## the patch's progress (patch_time).
## * Use: interact (hold to gather, repair, or upgrade; tap by day for the workbench or the
## shed), with something in reach (Interactions.focus_info()), whose word it shows (Gather,
## Repair, Upgrade, Workbench, Shop); dimmed when it would be refused now (the world label
## says why); its ring is the gather's, repair's, or upgrade's progress.
## * Build: build_mode (a tap) by day, and in build mode to leave it ("Done").
## Fear, Bomb, and Patch make a column at the attack stick's outer edge, Use and Build one at the
## move stick's (move_on_right; the Swap sticks setting flips it, apply_settings). Each column
## sits inside the safe area (MobilePort.safe_rect), clear of the HUD's widgets (reserved()),
## at the bottom of the room they leave, each button at least MobilePort.minimum_target()
## across. The action buttons show only while Pause does and the scarecrow can act (can_act: not
## frozen, the vacation not over, the scarecrow up).
## Each button is a STOP Control with a round hit area, so it takes its touches before the
## sticks (which read what the GUI leaves); this node is IGNORE, so the rest of the screen stays
## the sticks'. Hidden, a button takes no touches, so whatever is up (the dialogue's paper and
## Skip, a menu) gets them. A finger that lands on a button is that button's until it lifts. A
## pause, a freeze, hiding (a button or all of them), or the app leaving the foreground lets go;
## it processes while the tree is paused to hide them at once. In the desktop preview
## (-- --mobile) the mouse presses them too.
## Settings: in group &"touch_controls" (TouchSticks.GROUP) with apply_settings().
signal pause_requested
const PAUSE := &"pause"
const FEAR := &"fear"
const BOMB := &"bomb"
const PATCH := &"patch"
const USE := &"use"
const BUILD := &"build"
## Every button, in the order they're made.
const ALL: Array[StringName] = [PAUSE, FEAR, BOMB, PATCH, USE, BUILD]
## The input action each holds down while pressed (Pause has none: it asks, pause_requested).
const ACTIONS := {FEAR: &"fear", BOMB: &"offhand", PATCH: &"patch", USE: &"interact", BUILD: &"build_mode"}
const ICONS := {PAUSE: "pause", FEAR: "fear", BOMB: "pumpkin_bomb", PATCH: "patch", USE: "use", BUILD: "build"}
## Each one's word (Use's follows what's in reach; Build's is DONE in build mode; Pause has none).
const WORDS := {FEAR: "Fear", BOMB: "Bomb", PATCH: "Patch", USE: "Use", BUILD: "Build"}
const DONE := "Done"
## The columns, top to bottom: at the attack stick's outer edge, and at the move stick's.
const ATTACK_COLUMN: Array[StringName] = [FEAR, BOMB, PATCH]
const MOVE_COLUMN: Array[StringName] = [USE, BUILD]
## In canvas pixels: an action button across and Pause across (each at least the minimum
## target), between buttons, from the safe area's edge, and from a HUD widget above or below.
const SIZE := 92.0
const PAUSE_SIZE := 72.0
const GAP := 14.0
const EDGE := 16.0
const CLEAR := 12.0
## The backpack's count ("8/16") beside its icon (ResourceHud), kept clear with it.
const COUNT_WIDTH := 100.0
const FILL := Color(0.1, 0.24, 0.1, 0.7) # Sketch.SLOT, a little more solid
## A ring's unfilled part (as the portrait's), and each button's ring.
const TRACK := Color(0.32, 0.42, 0.5, 0.85)
const RING_COLORS := {FEAR: Color(0.36, 0.74, 1.0), BOMB: Color(1.0, 0.58, 0.18), PATCH: Color(0.98, 0.84, 0.38),
USE: Color(1.0, 0.86, 0.35)}
## The finger a mouse click stands for (the desktop preview has no touches).
const MOUSE := -2
var sim: FarmSim
## The move stick's half of the screen (TouchSticks.move_on_right): the move column goes there.
var move_on_right := TouchSticks.MOVE_ON_RIGHT
## Main: true while the game isn't being played (a menu is up); every button hides then.
var blocked: Callable
## The buttons by id (ALL).
var pads := {}
var _time := 0.0
## One round button: a STOP Control whose hit area is its circle, driven and drawn by its
## TouchButtons.
class Pad extends Control:
var id: StringName
var buttons: TouchButtons
## The finger holding it (-1: none; MOUSE: a click), the physics frame it went down in, and
## whether it lifted before a physics tick had seen it held.
var finger := -1
var down_frame := 0
var lifted := false
## What it shows: its word, its ring (0-1; -1: none), lit (fear or a bomb ready), dimmed (Use
## when it would be refused).
var word := ""
var ring := -1.0
var lit := false
var dim := false
func _init(p_id: StringName, p_buttons: TouchButtons) -> void:
id = p_id
buttons = p_buttons
name = String(p_id).capitalize()
mouse_filter = Control.MOUSE_FILTER_STOP
focus_mode = Control.FOCUS_NONE
visible = false
func held() -> bool:
return finger != -1
func _has_point(point: Vector2) -> bool:
return point.distance_to(size * 0.5) <= size.x * 0.5
func _gui_input(event: InputEvent) -> void:
buttons._pad_input(self, event)
accept_event()
func _draw() -> void:
buttons._draw_pad(self)
func setup(p_sim: FarmSim) -> void:
sim = p_sim
func _ready() -> void:
add_to_group(TouchSticks.GROUP)
process_mode = Node.PROCESS_MODE_ALWAYS # so a pause hides the buttons (and lets them go) at once
set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
mouse_filter = Control.MOUSE_FILTER_IGNORE # only the buttons take touches
for id in ALL:
var p := Pad.new(id, self)
pads[id] = p
add_child(p)
layout()
## The settings contract (group &"touch_controls", GameSettings.apply): Swap sticks puts the move
## stick on the left, and the button columns swap with it. A button held then lets go.
func apply_settings(s: GameSettings) -> void:
var right := TouchSticks.MOVE_ON_RIGHT != s.swap_sticks
if right != move_on_right:
let_go()
move_on_right = right
layout()
func pad(id: StringName) -> Pad:
return pads[id]
## Whether Pause shows: the game is being played (shown, and Main's menus aren't up: blocked), the
## tree isn't paused (a conversation, the pause menu), and no shop menu, pouch panel, sign, or end
## panel is over the farm. Hidden, a button takes no touches: what's up then gets them.
func playing() -> bool:
if sim == null or not is_visible_in_tree() or (blocked.is_valid() and blocked.call()) or get_tree().paused:
return false
for panel: UpgradePanel in [sim.upgrade_panel, sim.shed_panel]:
if panel != null and panel.is_open:
return false
return not ((sim.resource_hud != null and sim.resource_hud.open) or (sim.review_panel != null and sim.review_panel.visible)
or (sim.end_panel != null and sim.end_panel.visible))
## Whether the action buttons show (all but Pause): playing, and the scarecrow can act: not
## frozen (the intro), the vacation not over, the scarecrow up.
func can_act() -> bool:
return playing() and not sim.local_frozen and not sim.campaign.is_over() and sim.scarecrow != null and sim.scarecrow.alive
## Lets every button go (their actions released).
func let_go() -> void:
for id in ALL:
_release(pads[id])
func _notification(what: int) -> void:
match what:
NOTIFICATION_VISIBILITY_CHANGED:
if not is_visible_in_tree():
let_go()
NOTIFICATION_APPLICATION_PAUSED, NOTIFICATION_APPLICATION_FOCUS_OUT:
let_go()
func _process(delta: float) -> void:
_time += delta
layout()
var act := can_act()
for id in ALL:
var p: Pad = pads[id]
var show := _shown(id, act)
if p.visible != show:
p.visible = show
if not show:
_release(p)
if p.lifted and Engine.get_physics_frames() > p.down_frame:
_release(p) # a tap, now that a physics tick has seen it
if show:
_refresh(p)
p.queue_redraw()
## Whether a button shows (act: can_act()).
func _shown(id: StringName, act: bool) -> bool:
if id == PAUSE:
return playing()
if not act:
return false
match id:
BOMB:
return sim.combat.offhand == ScarecrowCombat.Weapon.PUMPKIN_BOMB
PATCH:
var kit := sim.scarecrow
return kit.patching or (kit.hp() < kit.max_hp()
and sim.campaign.state.resources.can_afford(sim.config.costs.get("patch", {}), kit.slot))
USE:
return not sim.interactions.focus_info().is_empty()
BUILD:
return sim.campaign.is_daytime() or sim.build.active
return true
## A shown button's word, ring, and state.
func _refresh(p: Pad) -> void:
p.word = WORDS.get(p.id, "")
p.ring = -1.0
p.lit = false
p.dim = false
var kit := sim.scarecrow
match p.id:
FEAR:
p.lit = kit.fear_left <= 0.0
if not p.lit:
p.ring = kit.fear_charge()
BOMB:
var cooldown := sim.config.bomb_cooldown
p.lit = sim.combat.bomb_left <= 0.0
if not p.lit and cooldown > 0.0:
p.ring = clampf(1.0 - sim.combat.bomb_left / cooldown, 0.0, 1.0)
PATCH:
if kit.patching:
p.ring = clampf(kit.patch_elapsed / maxf(sim.config.patch_time, 0.001), 0.0, 1.0)
USE:
var info := sim.interactions.focus_info()
if not info.is_empty():
p.word = info["label"]
p.dim = not info["ready"]
p.ring = info["progress"]
BUILD:
if sim.build.active:
p.word = DONE
p.modulate.a = 0.55 if p.dim else 1.0
# --- Touches ---
func _pad_input(p: Pad, event: InputEvent) -> void:
var touch := event as InputEventScreenTouch
if touch != null:
if touch.pressed:
_down(p, touch.index)
elif touch.index == p.finger:
_up(p)
return
var click := event as InputEventMouseButton # the desktop preview's mouse (a phone's taps are emulated clicks: not these)
if click != null and click.button_index == MOUSE_BUTTON_LEFT and click.device != InputEvent.DEVICE_ID_EMULATION:
if click.pressed:
_down(p, MOUSE)
elif p.finger == MOUSE:
_up(p)
func _down(p: Pad, index: int) -> void:
if p.held() or not p.visible:
return
p.finger = index
p.down_frame = Engine.get_physics_frames()
p.lifted = false
if p.id == PAUSE:
pause_requested.emit()
else:
Input.action_press(ACTIONS[p.id])
p.queue_redraw()
## The finger lifts: the action lets go, once a physics tick has seen it held (else in _process).
func _up(p: Pad) -> void:
if Engine.get_physics_frames() > p.down_frame:
_release(p)
else:
p.lifted = true
func _release(p: Pad) -> void:
if not p.held():
return
p.finger = -1
p.lifted = false
if ACTIONS.has(p.id):
Input.action_release(ACTIONS[p.id])
p.queue_redraw()
# --- Layout ---
## Places the buttons (every frame, and at once on apply_settings): Pause beside the day widget,
## the attack column at the attack side's outer edge, the move column at the move side's. A
## column sits at the bottom of the room the HUD's widgets leave it (nearer the thumb), and is
## squeezed (down to the minimum target) where that room is short.
func layout() -> void:
if pads.is_empty():
return
var safe := MobilePort.safe_rect(self)
var target := MobilePort.minimum_target(self)
var keep := reserved()
_column(ATTACK_COLUMN, not move_on_right, safe, target, keep)
_column(MOVE_COLUMN, move_on_right, safe, target, keep)
var side := maxf(PAUSE_SIZE, target)
var day := _day_rect()
var at := Vector2(day.position.x - GAP - side, day.get_center().y - side * 0.5)
at = at.clamp(safe.position + Vector2(EDGE, EDGE * 0.5), safe.end - Vector2(side + EDGE, side + EDGE))
_place(pads[PAUSE], Rect2(at, Vector2(side, side)))
func _column(ids: Array[StringName], right: bool, safe: Rect2, target: float, keep: Array[Rect2]) -> void:
var d := maxf(SIZE, target)
var x := safe.end.x - EDGE - d if right else safe.position.x + EDGE
var room := _room(x, x + d, safe, keep)
var n := ids.size()
var side := d
var gap := GAP
if n * d + (n - 1) * GAP > room.y - room.x:
gap = GAP * 0.5
side = maxf(target, (room.y - room.x - (n - 1) * gap) / n)
if right:
x += d - side # still at the edge
var y := maxf(room.y - n * side - (n - 1) * gap, room.x)
for k in n:
_place(pads[ids[k]], Rect2(Vector2(x, y + k * (side + gap)), Vector2(side, side)))
## The room down the safe area for a column from x0 to x1 (top, bottom): below each widget it
## passes in the screen's top half, above each one in the bottom half.
func _room(x0: float, x1: float, safe: Rect2, keep: Array[Rect2]) -> Vector2:
var top := safe.position.y + EDGE
var bottom := safe.end.y - EDGE
for r in keep:
if r.position.x >= x1 or r.end.x <= x0:
continue
if r.get_center().y < size.y * 0.5:
top = maxf(top, r.end.y + CLEAR)
else:
bottom = minf(bottom, r.position.y - CLEAR)
return Vector2(top, bottom)
func _place(p: Pad, r: Rect2) -> void:
if p.position != r.position or p.size != r.size:
p.position = r.position
p.size = r.size
p.queue_redraw()
## The HUD's widgets the buttons keep clear of, in canvas pixels, from those widgets' own layouts:
## the portrait and health bar (top left), the day widget and, once owned, the radar under it
## (top right), the backpack and its count (bottom left), the hotbar at its widest (bottom
## middle), and in build mode the build bar. (#43 fits the widgets into the safe area.)
func reserved() -> Array[Rect2]:
var w := size
var out: Array[Rect2] = []
out.append(Rect2(Vector2.ZERO, Vector2(ScarecrowHud.BAR_ORIGIN.x + ScarecrowHud.BAR_MAX_WIDTH,
ScarecrowHud.PORTRAIT_CENTER.y + ScarecrowHud.PORTRAIT_RADIUS + 6.0)))
out.append(_day_rect())
if sim != null and sim.campaign != null and Upgrades.owned(sim.campaign.state, "radar"):
var top := sim.phase_hud.bottom() + 8.0 if sim.phase_hud != null else RadarHud.MARGIN_TOP
out.append(Rect2(Vector2(w.x - RadarHud.MARGIN_RIGHT - RadarHud.MAP_SIZE.x, top), RadarHud.MAP_SIZE))
var bag := ResourceHud.ICON
out.append(Rect2(Vector2(0.0, w.y + bag.position.y), Vector2(bag.end.x + COUNT_WIDTH, -bag.position.y)))
var n := ScarecrowCombat.MAIN_WEAPONS.size() + ScarecrowCombat.OFFHAND_WEAPONS.size()
var bar := n * ScarecrowHud.SLOT.x + (n - 1) * ScarecrowHud.SLOT_GAP + ScarecrowHud.DIVIDER_GAP * 2.0 - ScarecrowHud.SLOT_GAP
var high := ScarecrowHud.HOTBAR_BOTTOM + ScarecrowHud.SLOT.y + 7.0 # (the slot in hand stands a little proud)
out.append(Rect2(Vector2((w.x - bar) * 0.5, w.y - high), Vector2(bar, high)))
if sim != null and sim.build != null and sim.build.active:
var m := StructureSystem.ORDER.size()
var bw := m * BuildHud.SLOT.x + (m - 1) * BuildHud.GAP + BuildHud.PAD * 2.0
var bh := BuildHud.HEAD + BuildHud.SLOT.y + BuildHud.HELP + BuildHud.PAD + BuildHud.BOTTOM
out.append(Rect2(Vector2((w.x - bw) * 0.5, w.y - bh), Vector2(bw, bh)))
return out
## The day widget (PhaseHud) in canvas pixels.
func _day_rect() -> Rect2:
if sim != null and sim.phase_hud != null:
return sim.phase_hud.widget_rect()
return Rect2(Vector2(size.x - PhaseHud.MARGIN.x - PhaseHud.WIDGET.x, PhaseHud.MARGIN.y), PhaseHud.WIDGET)
# --- Drawing ---
## A round button: a dark wash, its ring (a recharge or a channel's progress) or a glow when it's
## ready, an ink rim, its icon, and its word along the bottom; brighter while held.
func _draw_pad(p: Pad) -> void:
var c := p.size * 0.5
var r := p.size.x * 0.5 - 3.0
var seed := 600.0 + ALL.find(p.id) * 10.0
var color: Color = RING_COLORS.get(p.id, Sketch.GOLD)
p.draw_circle(c, r, FILL)
if p.held():
p.draw_circle(c, r, Color(Sketch.GOLD, 0.28))
if p.ring >= 0.0:
Sketch.circle(p, c, r - 2.0, TRACK, 5.0, seed)
Sketch.circle(p, c, r - 2.0, color, 5.0, seed + 1.0, -PI * 0.5, -PI * 0.5 + TAU * p.ring)
elif p.lit:
var pulse := 0.75 + 0.25 * sin(_time * 3.2)
for k in 3:
Sketch.circle(p, c, r + 2.0 + k * 3.0, Color(color, (0.32 - k * 0.08) * pulse), 4.0, seed + 2.0 + k)
Sketch.circle(p, c, r - 2.0, color.lightened(0.35), 5.0, seed + 5.0)
Sketch.circle(p, c, r + 1.0, Color(Sketch.INK, 0.85), 2.5, seed + 6.0)
var worded := p.word != ""
var side := r * (1.3 if worded else 1.4)
var at := c + Vector2(0.0, -r * 0.24 if worded else 0.0)
Sketch.icon(p, ICONS[p.id], Rect2(at - Vector2(side, side) * 0.5, Vector2(side, side)))
if worded:
var font_size := roundi(20.0 * p.size.x / SIZE)
while font_size > 12 and Sketch.text_width(p.word, font_size) > r * 2.0 - 6.0:
font_size -= 1
Sketch.text(p, Vector2(c.x, c.y + r * 0.36), p.word, font_size, Sketch.TEXT, HORIZONTAL_ALIGNMENT_CENTER, 6)

View file

@ -0,0 +1 @@
uid://um2exbsubbr5

View file

@ -3,22 +3,27 @@ extends Control
## The phone's controls (MobilePort; Main adds it over the HUD): two floating thumbsticks. A
## finger down on one half of the screen starts that half's stick where it lands; dragging tilts
## it (past the rim, the base follows the finger), and lifting the finger lets it go.
## * Move (right half): the move_* actions, as far as the stick is tilted. Screen up is
## forward, as with WASD.
## * Attack (left half): the aim_* actions, as a gamepad's right stick, and fire held while the
## stick is tilted past the aim dead zone, so the main weapon attacks that way each time it's
## ready.
## The sticks only take touches the HUD and the menus don't (their buttons get them first), and
## only while the scarecrow can act: not paused (menus, conversations), not frozen (the intro),
## not once the vacation is over. A pause or freeze lets both sticks go. Each stick is drawn only
## while a finger is on it.
## * Move (right half; the left with the Swap sticks setting, move_on_right): the move_*
## actions, as far as the stick is tilted. Screen up is forward, as with WASD.
## * Attack (the other half): the aim_* actions, as a gamepad's right stick, and fire held
## while the stick is tilted past the aim dead zone, so the main weapon attacks that way each
## time it's ready.
## The sticks only take touches the HUD and the menus don't (their buttons get them first, as do
## TouchButtons'), and only while the scarecrow can act: not paused (menus, conversations), not
## frozen (the intro), not once the vacation is over. A finger on a stick keeps it wherever it
## slides, over a button too (its drags and its lift are read before the GUI's). A pause or freeze
## lets both sticks go. Each stick is drawn only while a finger is on it.
## Settings: in group &"touch_controls" with TouchButtons; apply_settings() takes the Swap sticks
## setting (GameSettings.swap_sticks), and move_on_right_now() is the side in play (Prompts' tips).
## On phones a tap is also a left click (Godot's mouse emulation, which the buttons need), and
## the left click is fire: fire and offhand lose their mouse buttons here, so only the attack
## stick (or a paired gamepad) attacks.
enum Stick { MOVE, ATTACK }
const MOVE_ON_RIGHT := true # the move stick's half of the screen; the attack stick has the other
const MOVE_ON_RIGHT := true # the move stick's half of the screen by default (the user's call); the attack stick has the other
## The touch controls' group: GameSettings.apply calls apply_settings on each (#41).
const GROUP := &"touch_controls"
const RADIUS := 150.0 # base to rim, in canvas pixels (the 1920-wide canvas)
## Per stick: its left, right, up (forward), and down actions.
const ACTIONS: Array = [[&"move_left", &"move_right", &"move_forward", &"move_back"],
@ -26,6 +31,8 @@ const ACTIONS: Array = [[&"move_left", &"move_right", &"move_forward", &"move_ba
const COLORS: Array[Color] = [UiTheme.TEXT, Color(1.0, 0.5, 0.38)]
var sim: FarmSim
## The move stick's half: the right (MOVE_ON_RIGHT), or the left with Swap sticks (apply_settings).
var move_on_right := MOVE_ON_RIGHT
## Per stick (Stick): the finger on it (-1: none), its base, and its tilt (length 0-1).
var finger: Array[int] = [-1, -1]
var base: Array[Vector2] = [Vector2.ZERO, Vector2.ZERO]
@ -36,7 +43,28 @@ func setup(p_sim: FarmSim) -> void:
sim = p_sim
## The move stick's side in play: the move_on_right of the TouchSticks in the tree, else
## MOVE_ON_RIGHT (desktop, or before Main has added them).
static func move_on_right_now() -> bool:
var tree := Engine.get_main_loop() as SceneTree
if tree != null:
for n in tree.get_nodes_in_group(GROUP):
if n is TouchSticks:
return (n as TouchSticks).move_on_right
return MOVE_ON_RIGHT
## The settings contract (group &"touch_controls"): Swap sticks puts the move stick on the left.
## A stick held while it changes lets go.
func apply_settings(s: GameSettings) -> void:
var right := MOVE_ON_RIGHT != s.swap_sticks
if right != move_on_right:
let_go()
move_on_right = right
func _ready() -> void:
add_to_group(GROUP)
set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
mouse_filter = Control.MOUSE_FILTER_IGNORE # never in the way of the HUD's own buttons
for action: StringName in [&"fire", &"offhand"]:
@ -57,37 +85,46 @@ func _process(_delta: float) -> void:
let_go()
## A finger already on a stick: its drags and its lift, before the GUI sees them (so a button it
## slides over neither takes them nor stops the stick).
func _input(event: InputEvent) -> void:
var drag := event as InputEventScreenDrag
if drag != null:
for s in 2:
if finger[s] == drag.index:
_drag(s, drag.position)
get_viewport().set_input_as_handled()
return
var touch := event as InputEventScreenTouch
if touch != null and not touch.pressed:
for s in 2:
if finger[s] == touch.index:
_release(s)
get_viewport().set_input_as_handled()
## A finger landing where nothing else took it starts its half's stick.
func _unhandled_input(event: InputEvent) -> void:
var touch := event as InputEventScreenTouch
if touch != null:
if touch.pressed:
var s := side_of(touch.position)
if not can_act() or finger[s] != -1:
return
finger[s] = touch.index
base[s] = touch.position
tilt[s] = Vector2.ZERO
_apply(s)
get_viewport().set_input_as_handled()
else:
for s in 2:
if finger[s] == touch.index:
_release(s)
get_viewport().set_input_as_handled()
if touch == null or not touch.pressed:
return
var drag := event as InputEventScreenDrag
if drag == null:
var s := side_of(touch.position)
if not can_act() or finger[s] != -1:
return
for s in 2:
if finger[s] != drag.index:
continue
var d := drag.position - base[s]
if d.length() > RADIUS:
base[s] += d.normalized() * (d.length() - RADIUS)
d = drag.position - base[s]
tilt[s] = d / RADIUS
_apply(s)
get_viewport().set_input_as_handled()
finger[s] = touch.index
base[s] = touch.position
tilt[s] = Vector2.ZERO
_apply(s)
get_viewport().set_input_as_handled()
func _drag(s: int, at: Vector2) -> void:
var d := at - base[s]
if d.length() > RADIUS:
base[s] += d.normalized() * (d.length() - RADIUS)
d = at - base[s]
tilt[s] = d / RADIUS
_apply(s)
## Whether the scarecrow can take orders now (see the class notes).
@ -98,7 +135,7 @@ func can_act() -> bool:
## Which stick a finger landing at this point (canvas coordinates) starts.
func side_of(at: Vector2) -> Stick:
var right := at.x >= size.x * 0.5
return Stick.MOVE if right == MOVE_ON_RIGHT else Stick.ATTACK
return Stick.MOVE if right == move_on_right else Stick.ATTACK
## Lets both sticks go: their actions and fire released.