Input
That shape comes from two rules.
A control is an asset, and it carries every device. Not a key your code checks for — a thing with a name, a label a player reads, and a binding for keyboard, gamepad and touch. All three are required; a control missing one is refused when its map activates, naming what it lacks. A control that works on a desktop and not on a phone is the failure this prevents, so it is made unrepresentable rather than found later by someone holding a phone.
Nothing is live until something asks for it. No scheme is active by default. A controller activates the map it needs, and the live controls are exactly what awake components asked for. An empty world has an empty input surface and an empty screen — no phantom Jump button on a game with no jump.
Reading input
Subscribe. There is no per-frame polling API for gameplay.
public = {
inputMap = Field.assetRef("inputMap", "@builtin::inputMaps.default", NoSync, "The controls this component reads."),
speed = Field.number(5, NoSync, "World units per second at full deflection."),
jumps = Field.number(0, NoSync, "How many times the jump control was pressed."),
}
local controls
function awake()
controls = public.inputMap:activate()
controls.move:onInput(function(v, dt, active)
if not active then return end
local p = public.entity.position
local step = public.speed * dt
public.entity.position = { p.x + v.x * step, p.y, p.z - v.y * step }
end)
controls.jump:onPressed(function() public.jumps += 1 end)
end
function onDestroy()
public.inputMap:deactivate(controls)
end
Keep what activate returned and hand it back to deactivate: those
handles are this holder's claim on the map, and releasing the claim
disconnects the subscriptions made through it. See Holders below.
A component that moves a player's body from its controls like this (a
vehicle, a hovercraft, a jetpack, any movement that replaces the walking) is
the body's mover once its .metadata carries the bodyMover tag: launch
pads, knockback and speed boosts then reach it through Physics.setVelocity
and Physics.moverOf, as they reach the Controllers library's CharacterController. The
physics guide's "Movers" section (man topics/physics) lists what the tag
gives it.
onInput fires every frame the control is active, and once more on the
frame it goes inactive, carrying the neutral value and active = false.
That last call is what lets one handler both start and stop the motion it
drives — no second subscription to notice the release, and no state left
running because nothing told it to stop.
A control that is entirely input-driven needs no update(dt) at all.
The fourth argument, class, names the device class that drove the reading:
"kbm", "gamepad", "touch", "driven" while a script drives the
control, or "unknown" while a smoothing control coasts after its device
let go; it is nil on the drop frame. One control reads a mouse, a stick and a
finger in the same unit, and class is how a handler answers each in its
own way: the built-in follow cameras turn the view on the frame a mouse
moves, and ease a stick's or a finger's turn.
| Handler | Fires | On |
|---|---|---|
onInput(value, dt, active, class) | Every frame active, plus the drop frame | Any control |
onPressed() / onReleased() | The press and release edges | A button |
onCancelled() | The hold ended because the platform cancelled the touch holding it, in place of onReleased | A button |
onChanged(value) | When the value changes | Any control |
Every handler is on every control. A button answers onInput too — with
value as true while it is held — which is what you want for something
held rather than tapped: a sprint that lasts as long as the button does
reads the same way a stick does, and gets the drop frame when it ends.
onPressed is for the moment, onInput for the duration.
A touch the platform cancels ends a button without releasing it. Android
cancels a finger the system takes for a gesture of its own (a swipe from the
screen's edge) and one the touchscreen rejects as a palm; a browser's
touchcancel does the same. The button comes up, onInput gets its drop
frame, and onCancelled fires in place of onReleased, so a jump or a shot
fired on release does not fire when the system takes the finger. The same
cancel reads in Zin.state.mouseButtonCancelled for the pointer a finger
drives, Zin.virtual.buttonCancelled for an on-screen button,
Zin.state.keyCancelled for the key an on-screen button holds for a world
that polls keys, and the cancelled field of a mouse.up event.
A button already held when its map comes up (a sprint key held through the
flip to play, or through a respawn) reads held from the first frame, so
onInput reports it and the sprint carries on. Its press happened before the
control existed, so onPressed and onReleased stay quiet for that hold and
answer the next press: a map activated from inside another map's press handler
does not read that same press as a press of its own.
A control the map does not declare reads as nil, so a typo raises at the
subscribe call rather than becoming a control that never fires. A
controller that works with more than one map tests for one first —
if map.crouch then map.crouch:onInput(...) end — and loses only the
capability that control carries.
Authoring a scheme
An .inputMap is a folder, and its controls are the
<name>.inputBinding/ folders inside it — the same containment a
.toolbox has with its .tool children. Containment is what records the
reference, so a scene carrying its map carries every control it declares. A
scene pulled into another world cannot arrive somewhere boost binds to
nothing.
racer.inputMap/
init.luau -- { name = "racer" }
boost.inputBinding/
init.luau
steer.inputBinding/
init.luau
-- boost.inputBinding/init.luau
local B = require("@builtin::modules.zinput.bindings")
return {
label = "Boost", -- what the touch button shows, and what a
kind = "button", -- rebind screen calls this control
kbm = { B.key("ShiftLeft") },
gamepad = { B.padButton("left_shoulder") },
touch = { B.touchButton({ zone = "right-lower" }) },
}
A label is text as written, or an i18n.text value, which reads in the
player's language each time it is shown: label = i18n.text("hud.boost")
reads hud.json of the world's /zero/source/locales/<tag>/ catalogs, and
the engine's own controls are named in the built-in controls catalog
(i18n.text("controls.control.jump")). Code finds a control by its folder
name, so the label can read differently in every language and every
subscriber, rebinding and test that names the control keeps finding it.
kind | Shape per class | What it is |
|---|---|---|
button | an array — any one satisfies it | A press: jump, fire, interact |
axis1 | one binding | A scalar: throttle, zoom, lean |
axis2 | one binding | A vector: movement, look, aim |
A button takes an array because a control usually has more than one way to
be pressed on one device (ShiftLeft and ShiftRight). An axis takes one
because an axis evaluates one binding per class.
Set a class to false to suppress it deliberately — a text-entry control
with no touch counterpart says so, in the record where a reader sees it.
The inputAuthor toolbox writes these, filling in canonical defaults for a
control whose name it recognises, so a complete three-class binding is one
call rather than thirty lines.
Shaping an axis
An axis1 / axis2 control conditions its reading before a consumer sees
it. Four optional fields, applied in this order every tick:
-- steer.inputBinding/init.luau
return {
label = "Steer",
kind = "axis1",
deadzone = 0.05, -- magnitude under this reads nothing
curve = "quadratic", -- "linear" | "quadratic" | "cubic" | a function
invert = false, -- negate it
smoothing = 0.05, -- seconds it takes to approach a new reading
kbm = B.axis(B.key("KeyD"), B.key("KeyA")),
gamepad = B.padAxis("left_stick_x"),
}
On an axis2 the deadzone is radial — it is measured on the magnitude
of the pair, so a diagonal held past it keeps both components instead of
being clipped into a cross. "quadratic" squares while keeping the sign,
so a reading of 0.5 comes out 0.25 in the direction it came from.
The shaping lands on the reading the classes produced, after as /
unitsPerSecond / scale have brought each of them into the control's own
unit — so one deadzone, written once in that unit, covers every class
together. On a control measured in movement (look, zoom) that unit is
pixels or notches per frame, where a mouse and a finger read too, so a
stick's own dead zone and curve belong on the stick binding instead.
A stick's own dead zone and curve
A pad stick reads through a dead zone of its own before anything else
sees it: B.padStick and B.padAxis on a stick axis drop a deflection of
0.15 or less, the play a stick reports at rest and more as it wears, and
stretch the travel past it back over 0..1 so the reading starts at 0 at
the dead zone's edge. deadzone states another (deadzone = 0 reads the
stick as the device reports it), and curve bends the travel past it.
A binding that states no deadzone reads through the one the player chose
in the pause menu's Camera and controls section (camera.stickDeadzone,
camera_settings.current().stickDeadzone), 0.15 until they choose one:
-- look.inputBinding/init.luau
return {
label = "Look",
kind = "axis2",
kbm = B.mouseDelta(),
gamepad = B.padStick("right", { as = "delta", unitsPerSecond = 700, curve = "quadratic" }),
touch = B.touchDrag({ zone = "right" }),
}
Both act on the deflection, before as = "delta" integrates it, so they
are written in deflection whatever the control measures in, and the mouse
and the finger beside the stick are untouched. A pair is shaped on its
magnitude and keeps its direction. The shipped look reads its stick this
way: at the camera rigs' 0.005 radians per unit a full deflection turns the
view about 200 degrees a second, 0.6 about 56, and a stick resting under
the dead zone not at all.
A control's own deadzone and curve then act on what the stick binding
reports, so the two add up: on the steer above, the stick's 0.15 comes
first and the control's 0.05 is measured on the travel past it. A look
gate's stick (Zin.arming.gate) reads the stick through the control's
own binding of it, so the gate opens where that binding starts reading.
smoothing is the one that carries state: the value approaches its target
over that many seconds rather than stepping onto it, and a control whose
context leaves or whose group stands down drains to neutral the same way
instead of cutting.
A button refuses all four — it is held or it is not, so there is no
magnitude to cut, bend or approach.
More than one map
Maps compose. Several can be live at once and the player's surface is the union of them, so a capability brings its own controls with it:
-- Gun.component — a weapon adds Fire, and takes only Fire away
local controls
function onEquip()
controls = self.weaponMap:activate()
controls.fire:onPressed(function() self:shoot() end)
end
function onDrop()
self.weaponMap:deactivate(controls)
end
Fire appears beside the movement stick. Dropping the gun removes that one
button and nothing else. This is the common case, and it needs nothing but
activate / deactivate on the thing that has the capability.
Holders
Several things can hold the same map at once — two guns of the same kind, a
camera rig and the character it follows. Each activate opens its own
claim and hands back its own handles, and every subscription made
through those handles belongs to that claim.
deactivate(claim) releases one claim: the map leaves the live set only
when the last claim goes, and the subscriptions that claim made are
disconnected either way. So a rig releasing while the character keeps
playing takes the rig's handlers down and leaves the character's running,
and Zin.scheme.subscriberCount("jump") counts what is still listening
rather than everything that ever listened.
deactivate() naming no claim releases the caller's own most recent claim,
so a component that activated in awake gives up what it took even while
another holder stands on the same map; where the caller holds none of them,
the map's most recent claim goes. An asset ref is shared by every holder of
the same map, so the handles are what say which holder is releasing — name
the claim from a module or a helper, whose activate and release can run
under different callers. Subscribing through handles whose claim was
already released is an error: activate again, and subscribe through what
that call returns.
Zin.scheme.live() reports each live map's holders — how many claims are
still standing on it — and heldBy, one record per claim saying who opened
it: kind is "component" for an activation a component script made and
"execute" for one made from a bare call, entity is the entity a
component's activation sits on, source is the chunk:line it was opened
at, label is what the caller called it, and holder says the same thing
in a sentence. Pass that label as activate("weapon-swap").
That is what a control going silent under a suppression is asking about.
Zin.observe.whySilent(name) names the map standing the control down in
suppressedBy and that map's holders in suppressedByHolders, because the
map is not the thing to go and change — one of its activations is, and a
probe run once from an execute reads there beside the components.
Every activate reads the map's <name>.inputBinding/ children again, so a
control added, edited or removed since the map came up reaches the running
set — and reaches the holders already standing on it, whose handles and
subscriptions carry on across the edit rather than being replaced.
The other case is one thing taking over: in a car you must not still be able to jump, and with a menu open nothing in the game may answer at all. A map names the group its controls belong to, and the groups it stands down while it is live:
-- driving.inputMap/init.luau
return {
description = "Steering, throttle, brake.",
group = "vehicle",
suppresses = { "player" },
}
-- Car.component
local controls
function onDriverEntered()
controls = self.drivingMap:activate()
controls.throttle:onInput(function(v, dt) self:accelerate(v, dt) end)
end
function onDriverExited()
self.drivingMap:deactivate(controls)
end
The car never touches the walk map. It stands down the whole player
group by naming it, and walking resumes the moment the car releases —
which is what has to happen, because the car still exists after the
player gets out. Liveness follows who has control, not what exists:
awake / onDestroy are the wrong hooks for anything a player enters and
leaves.
A suppressed map keeps its holders, its handles and every subscription made through it. It stops reading devices and its buttons leave the screen; a stick held at the moment it stands down reports its neutral value once, so whatever it drove stops rather than sticking.
A press made while a map stands down is not that map's. When the suppressor
lets go, a button still held from that press reads held (so a held sprint
keeps sprinting) and fires neither pressed nor released for it, and a
press in the same frame stays the suppressor's however many ticks that frame
runs. So a menu that stands the player down and closes on the press of a key
both maps bind keeps that press to itself: the player's control answers from
the next press. A button a control answered before its map stood down, still
held when the suppressor lets go, is still that control's: its release fires
released, so a control that starts something on pressed and stops it on
released stops it.
Declaring neither field composes with everything — right for a map that is
the only thing a world runs. A map that declares no group belongs to one
named after itself, so it can still be named by something that wants to
stand it down.
A menu is the same mechanism pointed at everything:
return { group = "ui", suppresses = { "player", "vehicle", "weapon" } }
Zin.scheme.live() reports each map's group, what it suppresses, and
its suppressedBy — the answer to "this control is live and nothing
happens".
The cursor
A map that steers with the mouse declares pointerLock = true (the
engine's @builtin::inputMaps.default does), and while it is live in a
running world the engine asks for the cursor: it is captured on the next
click on the window, plain mouse movement turns the camera, and Escape or
losing focus gives it back until the next click.
A suppressed map stands its pointer lock down with its bindings. So the menu map above frees the cursor the moment it is activated, every click lands on the menu, the look control reads nothing behind it, and the cursor is taken again on the next click once the menu map is deactivated. A menu written this way needs no pointer code of its own.
A shown screen that takes pointer input holds the pointer the same way,
with no input map involved. A screen holding an open modal holds it, and
so does a screen with a shown widget stating holdsPointer = true (a pause
menu or an inventory built from containers):
ui.registerScreen("pause", { type = "modal", id = "pauseModal", props = { title = "Paused" },
children = { { type = "button", id = "resume", props = { text = "Resume", onClick = "resume" } } } }, 900)
ui.registerScreen("inventory", { type = "vertical", id = "bag", props = { holdsPointer = true },
children = { --[[ slots ]] } }, 800)
While such a screen is shown the cursor is the person's: the lock stands
down, the cursor shows, clicks land on the screen and the look control has
no locked pointer to read. Every holder keeps its ask, so hiding the screen
brings the lock back as the game asked, on the next click on the window. A
HUD with buttons holds nothing unless one of its widgets says so, so a game
steering with the mouse keeps the cursor under its HUD, and a modal stating
holdsPointer = false leaves the cursor to the scene.
The ask is held by named holders: the scheme holds it as Zin.scheme for
the maps that declare it, and a script can hold it under its own name:
Zin.pointer.lock("myGame.aim", "the aiming camera steers with the mouse")
Zin.pointer.unlock("myGame.aim") -- this holder's ask goes
Zin.pointer.unlock() -- every holder's ask goes
Zin.pointer.status() answers who is asking and what the engine made of
it, in one read that leaves the input observation as it stands:
Zin.pointer.status()
--> { requested = true, locked = false, suppressed = false, armed = false,
-- holders = { { holder = "Zin.scheme",
-- reason = "inputMap 'default' declares pointerLock and is live" } },
-- uiHolders = {},
-- why = "asked for by Zin.scheme; captured on the next click on the window" }
suppressed is true while the cursor belongs to the person (gameplay
paused, a shown screen holding the pointer, or the editor sharing the
window with no scene picture on it), which holds a standing ask ungranted.
uiHolders names the shown screens holding the pointer, and
Zin.state.uiHoldsPointer() reads that list alone. Zin.pointer.holders(),
Zin.pointer.requested() and Zin.pointer.locked() read the parts alone.
Which way is forward
Two frames, and which binding speaks which:
- Stick bindings —
B.wasd(),B.padStick(),B.touchStick()— report the direction the player means. Forward is+y. Amoveaxis carrying a keyboard class and a stick class drives both devices the same way. - Delta bindings —
B.mouseDelta(),B.touchDrag()— report screen-space movement. Down is+y, because that is what the pointer did.
The platforms underneath keep their own signs; the conversion happens at the binding, which is the layer where a keyboard class and a stick class meet on one axis.
Where a point is
A pointer position, a touch, every input.events() position and a
worldToScreen projection are in the scene viewport's physical pixels,
measured from the top-left of the rect the scene is drawn into.
screenToRay and Physics.raycastScreen take the same space, so a pointer
position goes straight into a ray cast. The UI lays out in logical
points: ui.fromViewport(x, y) carries a point onto the HUD's canvas
(ui.screenSize()), ui.fromViewport(x, y, "window") onto the window where
ui.hitTest and gui.bounds answer, and ui.toViewport carries one back.
local m = input.snapshot().mouse_position
local w = ui.fromViewport(m[1], m[2], "window")
local over = ui.hitTest(w.x, w.y) -- the widget under the pointer
guides { path = "topics/screen-coordinates" } covers both spaces, a marker
over a world point, an arrow at the screen edge for a point off screen or
behind the camera, and casting a point on the UI into the scene.
Gamepad
Pad buttons are named by position, never by the letter printed on them:
south, east, west, north, left_shoulder, right_shoulder,
left_trigger, right_trigger, left_stick, right_stick, select,
start, guide, and the four dpad_*. south is the lower face button
on every pad, so one binding evaluates against any of them.
A name reaches a button through the same resolution everywhere: case and
word separators fold away, so "South" and "LeftShoulder" reach the
buttons the canonical spellings name, and a name outside the list is
refused with the list in the message. Key names resolve the same way
against the KeyboardEvent.code vocabulary ("KeyW", "Space",
"Enter", "ShiftLeft"), with a single letter or digit accepted as
shorthand for its Key<L> / Digit<N> code, so a simulated press lands
on the code a keyboard reports rather than under a name only the simulator
can press.
Which glyph a prompt draws is a display concern the binding layer never
sees. Zin.gamepad.label("south") resolves it from the connected pad —
A on an Xbox pad, Cross on a PlayStation one, B on a Nintendo one.
ui.text("Press " .. Zin.gamepad.label("south") .. " to jump")
Zin.gamepad also answers how many pads are connected and which family
each belongs to — what a local-multiplayer lobby needs.
Naming a slot on a binding picks one pad; omitting it means any connected
pad, which is what a single-player scheme wants: whichever controller the
person picked up drives the control, with no pairing step. A string in the
slot's place names a device by a piece of its name or id, whatever slot it
took: a wheel and its separate pedals are two devices, each found by name.
Menus on a pad
A game's menus work on a pad with no pad code. While a menu is on screen,
meaning a shown screen holding the pointer (an open modal, or a widget
stating holdsPointer = true, see The cursor), every connected
pad drives it:
- the d-pad and the left stick move focus in the direction pressed, by where the widgets stand on screen: to the next row (or column) of widgets that way, at the widget of it closest across, so down goes to the next line of a settings list wherever its control sits in the line, and to the cell straight below in a grid. Holding repeats. The arrow keys move focus the same way from a focused button.
southpresses the focused widget, the way Enter does: a button clicks, a checkbox toggles. On a focused slider, left and right step its value.eastis Back (see Back): an open popup'sonDismiss, a dismissible modal'sonClose, else the world's own claim holding Back (Zin.back.claim). With none of these,eastdoes nothing, in the editor's play as at runtime.startis the app's pause action and opens the app menu, unless the game's own menu takes it (see Escape and Start for the game's own menus).
A menu opens with its first widget in reading order focused when the last
device used was a pad or a keyboard, and the focus ring shows where focus
is. A menu that opens before any pad or key was used opens with nothing
focused, and its first direction press focuses that first widget, so a menu
needs no ui.focus of its own to be ready for a pad. A HUD holding no pointer
is no menu, so the pad keeps playing the game under it.
While a menu takes them, the d-pad, south, east and the left stick read
released and centred to the game's bindings, and their events carry
consumed_by_ui, so a pad-bound jump does not fire under the pause menu.
Zin.gamepad.get(slot).ui_buttons names what the menu holds.
Two props shape the moves where the nearest widget is not the right one:
navUp,navDown,navLeft,navRighton a widget name the id of the widget that direction goes to from it (the last tab wrapping to the first, a "Back" button reached from anywhere in a column).navGroup = trueon a container keeps directional moves among the widgets inside it: from inside, a direction goes to the nearest widget inside, and stays put when there is none. An open modal holds focus inside it the same way.
ui.registerScreen("settings", { type = "vertical", props = { holdsPointer = true }, children = {
{ type = "horizontal", id = "tabs", props = { navGroup = true }, children = {
{ type = "button", id = "tab_video", props = { text = "Video", onClick = "showVideo", navLeft = "tab_audio" } },
{ type = "button", id = "tab_audio", props = { text = "Audio", onClick = "showAudio", navRight = "tab_video" } },
} },
{ type = "button", id = "back", props = { text = "Back", onClick = "closeSettings" } },
} }, 40)
Zin.surface.current() reads "gamepad" once the player uses a pad, so a
prompt reads Zin.gamepad.label("south") then. A suite drives all of it with
the simulator: inputSim.pad connects a pad, padPress("dpad_down") moves
focus, padPress("south") presses, and ui.focusedWidget() names where focus
stands. Arrow keys reach the menu with the "ui" target
(inputSim.key("ArrowDown", nil, "ui")); a key with no target goes to the
game.
Wheels, pedals, flight sticks and other controllers
The canonical layout covers a standard pad. Every controller also reports its own elements, every axis and button, in the device's order, and those are read and bound by their 0-based index, so a steering wheel, separate throttle / brake / clutch pedals, an H-shifter, a flight stick (joystick) with its throttle and rudder, a HOTAS or a button board with thirty buttons is as bindable as a pad.
Zin.gamepad.device(slot) says what a controller is and what it reports:
its name, a stable id for the model, vendor / product where the
platform states them, axisCount and buttonCount, and each element with
its index, the canonical name it also drives (on a standard pad), and
for an axis the native range min..max the device reports it in. A binding
screen lists these; Zin.events reports each change as gamepad.device_axis
/ gamepad.device_down / gamepad.device_up with the element's index, so
"move the control you want" captures it.
Zin.state.padAxis(index, slot) reads a device axis as -1..1 across its
native range, and padDown(index, slot) / padButtonValue(index, slot) a
device button. Bindings take the index where they take a canonical name:
-- steer.inputBinding/init.luau: the wheel is its own device, found by name
local B = require("@builtin::modules.zinput.bindings")
return {
label = "Steer",
kind = "axis1",
kbm = B.axis(B.key("KeyD"), B.key("KeyA")),
gamepad = B.padAxis(0, { slot = "wheel" }),
touch = B.touchStick({ zone = "left", axis = "x" }),
}
-- throttle.inputBinding/init.luau: the throttle pedal drives forward, the
-- brake pedal back; each reads -1 released and 1 floored, so `rest = -1`
-- reports 0..1
return {
label = "Throttle",
kind = "axis1",
kbm = B.axis(B.key("KeyW"), B.key("KeyS")),
gamepad = B.axis(
B.padAxis(1, { slot = "pedals", rest = -1 }),
B.padAxis(2, { slot = "pedals", rest = -1 })
),
touch = B.touchStick({ zone = "left", axis = "y" }),
}
-- shiftUp.inputBinding/init.luau: the wheel's twentieth button
return {
label = "Shift up",
kind = "button",
kbm = { B.key("KeyE") },
gamepad = { B.padButton(19, "wheel") },
touch = { B.touchButton({ zone = "right-upper" }) },
}
rest and full calibrate a device axis: the binding reports
(reading - rest) / (full - rest), so rest reads 0 and full reads 1. A
pedal wired the other way takes { rest = 1, full = -1 }, a wheel whose
centre sits off zero { rest = 0.02 }. One axis carrying a throttle and a
brake (combined pedals) splits into two arms that each count their own side:
B.axis(B.padAxis(1), B.padAxis(1, { full = -1 })). With no connected device
reporting the axis, the binding reads 0, so a pedal map stays quiet until the
pedals are plugged in and the keyboard drives the control. Deadzone, curve, invert
and smoothing come from the axis shaping above, the same as for any binding.
On the desktop every element the platform lists is read, and on Linux each axis reports where it rests the moment the controller connects. In the browser, the elements are the ones the Gamepad API reports for the controller; a controller the browser lays out as the standard gamepad names its first seventeen buttons and four axes canonically and reports any further element by index.
Rumble and force feedback
A controller's haptic output, vibration and force feedback alike, is played
from Zin.gamepad.
Zin.gamepad.rumble(slot, { strong, weak, leftTrigger, rightTrigger, seconds }) plays the pad's motors, strong the low-frequency body motor,
weak the high-frequency one, the triggers' motors where the pad has them,
each 0..1, for seconds. A new rumble replaces the one playing, so a game
calling it each tick with the strength of the moment drives the motors
continuously; Zin.gamepad.stopRumble(slot) stops it. With no slot it plays
on every connected pad that offers the motors asked for.
Zin.gamepad.force(slot, { constant, spring, damper, friction }) holds
force-feedback effects on a wheel or stick's own axes. constant is a force
-1..1 along the device's first axis (a wheel's rotation), a positive and a
negative level pushing it opposite ways. spring pulls the axis back toward
a centre, damper resists its speed and friction resists any movement;
each takes a strength
-1..1 or { strength, saturation, center, deadband }. Each effect named
holds until the next call and each one left out stops, so a driving game
calls it every tick with the forces of the moment:
-- the tyres' aligning torque pushes the wheel back, and the centring
-- spring stiffens with speed
Zin.gamepad.force(wheelSlot, {
constant = -aligningTorque / maxTorque,
spring = { strength = math.clamp(speed / 30, 0.1, 0.8) },
damper = 0.15,
})
Zin.gamepad.stopForce(slot) releases them all. Leaving play stops every
rumble and releases every force effect, so a wheel a game was pushing goes
slack the moment the game stops.
Zin.gamepad.capabilities(slot) states which outputs reach a pad on this
platform and device, each { supported, reason? }: rumble,
triggerRumble, constant, spring, damper and friction. A rumble or
a force effect the pad does not offer refuses with that reason. What each
platform offers:
| Output | Linux | Windows | macOS | Browser |
|---|---|---|---|---|
| rumble | where the device has motors | where the device has motors | none | where the browser exposes vibrationActuator (dual-rumble) or hapticActuators |
| triggerRumble | none: the desktop backend drives the body motors only | none: the desktop backend drives the body motors only | none | where the browser offers trigger-rumble |
| constant, spring, damper, friction | each one the device lists among its force-feedback effects (evdev) | none: the Windows backend drives the rumble motors only | none | none: the Gamepad API has no force effects |
The pad's record (Zin.gamepad.get(slot)) carries what plays: rumble
with how long is left, and force with each effect it holds, each with
error when the device itself refused it.
The device's own haptics
The phone or tablet in the person's hands vibrates through
input.deviceHaptic(effect): "tick" (the lightest, for a pick),
"click" (a press confirmed) or "heavy" (a firm knock), played on the
frame that follows the call, which an engine at rest runs at once.
input.deviceVibrate(seconds, amplitude?) holds the
motor for up to 5 seconds, at amplitude 0..1 where the device sets one.
Both answer true once queued, or (false, reason) on a device with none,
and raise nothing, so a game calls them on every press without asking first.
input.deviceHaptics() states what the device offers: platform,
supported, reason, amplitude, effects, and the record of what was
asked (requested, played, refused, and last with the platform's
answer and when it came).
| Android | Web | Desktop | |
|---|---|---|---|
| effects | the platform's predefined touch effects, silenced by the system's touch-feedback setting | a short navigator.vibrate, where the browser offers it (Chrome on Android; not Safari) | none: the computer has no motor of its own |
| vibrate | the vibrator, at an amplitude where it sets one | navigator.vibrate at the browser's strength | none |
A browser vibrates only once the person has touched the page; a request
before that is answered refused with the browser's reason. On the web,
played is the browser taking the request: a browser offers
navigator.vibrate and answers it true on a device with no motor too
(most tablets), so the web reads supported wherever the browser offers
vibration. The Android app reads the device's own vibrator, and on a
device with none states supported = false.
Hand controllers in a headset
While an XR session holds input focus the two hand controllers present as one
pad, so a game written against its input maps plays in a headset with nothing
added: every map's gamepad bindings answer them. The left stick is the pad's
left stick (move), the right stick its right stick (look), A and B are
south and east (jump, crouch), X and Y are west and north
(interact), the grips are the shoulders, the triggers the triggers, the
thumbstick clicks the stick clicks (sprint on the left), and the left menu
button is start. The pad is connected while a controller is held and gone
when the session loses focus. Using a controller's buttons or sticks makes
Zin.surface report "gamepad", so prompts draw pad glyphs, and the touch
overlay does not mount.
Turning is inside the look action. The right stick's horizontal axis
reaches look as discrete steps of 45 degrees: one flick of the stick is one
step, and the stick returns to rest before the next flick turns again. The
person can choose smooth turning instead (xr.setTurnMode("smooth"), or
--xr-turn smooth at boot). Either way the game turns its own camera and the
headset follows the camera's yaw. The stick's vertical axis never reaches
look, because the head owns pitch and the view is never tilted by a stick.
A step is 45 degrees at the look sensitivity every shipped camera rig
defaults to (0.005 radians per look unit); a rig authored with another
sensitivity turns in proportion.
Movement follows the view. The camera a game moves relative to is the rig
in a headset, and the person looks along the rig turned by their head. The
Camera component's forward, right and up report that facing, so the
character controller, the editor fly camera and every game that moves along
camera.active()'s Camera.forward go where the person looks, with no change
of their own. Turning the head turns the view and never the rig: the rig is the
camera entity's position and yaw, so a stick pushed forward walks along the view
while the head turns freely.
Pointing follows the controller. The pointer ray the engine casts for
hover and selection (getPointerHitTable()) is the dominant hand's aim pose while the
session holds input focus; xr.pointerRay() returns it. The same laser is the
game's mouse: input.snapshot().mouse_position is the point it rests on seen from
the game's camera, every frame and with no press, so hover reacts under it, and a
ray built from that position (screenToRay at the mouse) is the laser's own ray.
xr.pose(role) reads
where the head or a hand is in world space (xr.roles() lists the roles
tracked now, and a device that follows another part of the body is read the
same way), xr.controller(hand) reads a controller's sticks and buttons, and
xr.pulse(hand, amplitude, seconds) vibrates it. man xr lists the whole
surface.
Controllers cannot be pressed by a script, so the inputSim xr verb injects
their state where the runtime's action set enters the engine
(tools.use("inputSim", "xr", "left_hand", "thumbstick", { 0, 1 })): the pad, the
turning, the pointer ray and xr.controller follow it as they follow held
controllers. xrHead injects the head pose in the tracking space (both eyes
move with it, so the picture, xr.pose("head") and the facing the Camera
component reports follow). xrOff hands every control and the head back to the
runtime.
Touch
On a touch surface the on-screen controls appear by themselves, built from
the live bindings. A binding with a touchStick gets a stick; one with a
touchButton gets a button labelled from the binding's label. Nothing
appears that no live binding declares.
A map that stands the player group down — suppresses = { "player" },
which is what the builtin controls belong to — takes those controls off the
screen for as long as it is live; it needs no control of its own when
standing the player down is all it does.
The overlay and a game's own screens share the picture. A widget of a game
screen that answers a press (a button, a slider, a list that scrolls, a box
with onClick) and lies over a button, the fan or an open sheet entry (the
rows of a settings panel or a menu) takes the presses landing there: the
button gives way, claiming no touch, until the widget goes, and its place
stays in ui.safeArea().controls so a screen's anchors keep clear of it. A
widget a press does nothing to (a label, a HUD readout, a full-screen tint)
leaves the button standing and pressable.
Zin.touchControls.layout().yielded lists the buttons giving way, each naming
the widget (yieldedTo). A column button giving way is drawn nowhere. A
corner button (the app's Menu button, and any place = "corner" button) is
drawn dimmed: a tap on the widget reaches the widget, a finger held still on
it for the entry's holdSeconds (0.9 s) presses the button and clicks nothing
under it, so the player can open the app menu from a full-screen panel, and a
tap on its circle out of a press's reach of every widget presses the button
at once. A widget using a held or dragged press (a slider, a press-and-hold
button, a drag surface) keeps a finger resting on it: there two fingers held
still together on the circle for holdSeconds press the button, and the entry's
holdFingers states how many its centre takes.
B.touchButton(opts) shapes the layout:
| Opt | Default | Effect |
|---|---|---|
id | see below | The button's identity in Zin.virtual, the name code presses, gates and taps it by |
priority | 50 | Lower renders first / more prominently |
size | "medium" | This button's circle radius: 40 / 56 / 72px |
group | none | Buttons sharing a group render adjacently |
place | "column" | "column": the action column at the bottom-right. "corner": the top-right corner of the safe area |
icon | none | A glyph drawn on the circle in place of the label |
A button of a button control that states no id takes the control's
name; any other takes a text label, else the catalog key of an
i18n.text label, else its zone (Zin.bindings.touchButtonId). An
axis1 worked by two buttons gives each an id when something names
them, as Zin.arming.gate { virtualButtons = { "Up", "Down" } } does.
size is per button: a scheme mixing a large action button with a
small pause pip draws them at 72 and 40 whatever else is on screen, and
Zin.touchControls.layout() reports each button's own radius. The
overlay budgets buttons into a two-column band on the right edge, packing
the column on the largest live button's pitch — so the set decides where a
button sits, and the button's own size decides how big it is. A scheme
with more than four walks every button one step down its own size, which
layout() reports as appliedSize beside the declared size; past the
two-column budget the overflow collapses behind a fan that opens on tap.
Set priority on the controls a player reaches for without looking, and
group on clusters that read as one gesture.
A button whose place is "corner" sits in the top-right corner of the
safe area instead, in a row growing leftward along the top edge (a row ends
at the look area's left edge, 40% across, and the next button starts a row
below it), and the column's band starts below those rows. The app menu's
own Menu button (the pause action, @builtin::inputMaps.app) is one: it
takes the same small place on every screen whatever the column holds, so
the bottom-right corner, where a thumb works the game, is the game's. A
game that draws its own touch controls reads where every button the engine
draws sits from Zin.touchControls.layout() (each entry's place, cx,
cy and radius) and keeps its controls clear of them; Escape and a
gamepad's Start reach the same menu. It states the regions its controls
hold with input.setTouchClaims under an owner name of its own, and a
contact beginning on one is the game's: it presses no button, stick or look
area the engine draws beneath it.
Styling the overlay
Zin.touchControls.setAppearance(opts) states how the overlay is drawn,
so a game that typesets its own interface puts the controls the engine
draws in the same faces, colours and margins:
Zin.touchControls.setAppearance({
inset = 38, -- the margin the column keeps from the edges
gap = 20,
fill = "#10243aa0",
stroke = "#c9a227",
strokeWidth = 2,
textColor = "#f2e6c8",
fontFamily = "Inter", -- any family `ui.listFonts()` names
fontScale = 0.36,
})
inset and gap decide where the buttons sit. The column keeps inset
from the edges of the safe area, the part of the screen no status bar,
navigation bar, camera cutout or on-screen keyboard covers
(ui.safeArea()), so on a phone the controls stay clear of all of those
on their own; a game keeping a margin of its own states it here and the
touch controls keep it too. The game's own screens keep clear of the
controls in turn: ui.safeArea().controls lists the rect each drawn button
covers (owner "zin_touch_controls"), and a box an anchor pins to a corner
moves out from under them on its own. fill / stroke / strokeWidth draw each circle, textColor /
fontFamily / fontScale its label, iconFont / iconScale an icon
glyph, sheetFill / sheetRounding the overflow sheet, fanFill /
fanStroke the fan, and stickStroke / stickFill / stickWidth the
movement stick. A call states only the keys it carries; calling it with
no argument restores the engine's own.
A single button states any of the button keys for itself, over whatever the overlay is set to:
local Icon = require("@builtin::modules.icons")
B.touchButton({
zone = "right-lower", label = "Fire", icon = Icon.Bomb,
fill = "#7d1d1d", stroke = "#e8b33a", size = "large",
})
icon is a glyph drawn in the label's place, set in iconFont - which
defaults to phosphor, the family modules.icons names. appearance()
reports what is in force, and each entry of Zin.touchControls.layout()
carries the style its own button resolved to.
Back
Back is the platform's own: the Back button and back gesture of an Android
phone, and a keyboard's Back key (BrowserBack, the name a browser gives it
too). A pad's east button is Back while a menu is on screen (see
Menus on a pad) and something stands to take it: an
overlay, or a claim of the world's own. The editor's claim that leaves play
stands for the platform's own Back (platform = true), so a pad's east
passes it by and never stops play. The
engine routes every press to the first of these that stands:
- the topmost overlay on screen that states how it is dismissed, an open
popupcarryingonDismissor an open, dismissiblemodalcarryingonClose. Its dismissal runs, exactly as Escape runs it, so a menu or dialog built from those closes on Back with no code. - a claim on Back,
Zin.back.claim(handler): the highest priority, and the most recent among equals, runs its handler. - nothing: the platform's default answers. On Android the app moves to the background; a desktop window and a browser page stay where they are.
A claim states ahead of the press that the world takes Back, which is what Android asks before a back gesture begins. Hold one while Back means something (a pause screen to bring up, a sub-menu to step out of) and release it when Back should leave:
local Zin = require("@builtin::modules.zinput")
local claim
local function resume()
pauseScreen.hide()
if claim then claim:release() claim = nil end
end
local function pause()
pauseScreen.show()
claim = Zin.back.claim(resume)
end
A claim a component makes is released when its entity is destroyed. The
editor claims Back at priority -1 while a scene is played, so Back stops
play once nothing in the world takes it. Zin.back.press() presses Back
from a script, routed the same way. Each press is a back event in
input.events(), { kind = "back", taker = "overlay" | "claim" | "none" }.
Escape and Start for the game's own menus
Escape, a pad's start and the on-screen Menu button are the app's pause
action: the menu control of @builtin::inputMaps.app, in group app,
which the app menu holds in every profile and every world. Pressed with
nothing of the game's in the way, it opens the app menu over the world.
A game takes that press for its own pause screen, or to close its own menu
first, with an input map that suppresses the app group, live exactly while
the game's screen is up. One press reaches one owner, in this order:
- the game's map that suppresses
app, while it is live: its control answers, and the app menu does not see the press; - the app menu, once no live map suppresses
app.
The game's map stays live until the game lets go of it. Letting go of it from the handler of the press that closed the screen keeps that press the game's: the app menu answers from the next press, never the same one (see More than one map for the rule).
-- pause.inputMap/init.luau: live while the game's pause screen is up.
return {
label = "Pause screen",
description = "Escape and Start close the pause screen.",
group = "pauseScreen",
suppresses = { "app", "player" },
}
-- pause.inputMap/close.inputBinding/init.luau
local B = require("@builtin::modules.zinput.bindings")
return {
label = "Resume",
kind = "button",
kbm = { B.key("Escape") },
gamepad = { B.padButton("start") },
touch = { B.touchButton({ label = "Resume", place = "corner", size = "small" }) },
}
-- Pause.component: the game's own pause screen on Escape and Start.
local controls
local function resume()
pauseScreen.hide()
self.pauseMap:deactivate(controls)
controls = nil
end
function pause()
pauseScreen.show()
controls = self.pauseMap:activate()
controls.close:onPressed(resume)
end
The press that opens the game's pause screen is the game's own control,
live while the game plays (a pause control on its own key, or one it binds
to Escape in a map that suppresses app for as long as the game wants the
pause action). While a map suppressing app is live, Escape and Start do
not reach the app menu, so a game that holds one through its play puts the
app menu on its own pause screen, a button calling appMenu.open(). The
inputAuthor toolbox writes the binding for you:
{ name = "close", from = "menu" } copies the pause action's Escape, Start
and Menu button.
Back (Android's Back, the back gesture, a pad's east on a menu) is a
different press with its own route, above: a game that wants its menu
closed by Back as well holds a claim (Zin.back.claim) while the menu is
open, beside its map.
Testing it on every device
The inputSim toolbox drives all three classes and reads back what
actually reached the game. A world checked only from a keyboard is a world
whose keyboard experience is the only one anybody verified.
- device — present as a phone, a desktop, or a pad.
- bindings — which controls are live.
- layout — what is on screen.
- tapButton — tap a named control where a player would.
- fired — what reached the game.
- held — what is still down.
action drives a control by name — move, jump, whatever bindings
lists — with the value the game should read, which is how to play a game from
a script: the same call works whatever device the player would hold. The value
joins the control like another device (Zin.scheme.drive is the layer
underneath; Zin.test.action the test helper), so shaping, edges, contexts and
suppression all apply, and fired reports it under the class driven.
What inputSim simulates is the game's: it reaches the scene whatever a
person at the window has focused, and no UI widget receives it, so a run
testing the game and a person typing into an editor panel never reach into
each other. Pass "ui" as a verb's trailing target to reach the UI the way
a person's device does.
The point click and mouseMove take is in physical pixels, in the space
their receiver reads positions in. For the game (the default) that is the
space capture and worldToScreen report, the scene's own pixels. For the UI
("ui") it is the window, where every widget is recorded: a gui.bounds rect
times ui.pixelRatio(), wherever the widget's screen draws.
Read bindings first. Nothing is live until a component activates a map,
so an empty list means no awake component asked for input — a different
problem from a control that fires and does nothing.
fired is what turns a simulated input into an assertion: it reports which
controls fired since you last asked and from which device class, and clears
as it reads. A capture can look identical whether or not the input landed.
Each row belongs to one live map, so a control name two maps both declare
reports once per map under the map's own name and count. The row also carries
subscribers and delivered, which is how a press that fired and reached
nobody reads apart from one that reached the game.
layout is how a control nothing consumes gets caught — a label on screen
with no matching entry in bindings.
held names what the session still has down — keys, mouse buttons, contacts,
the on-screen stick, connected pads — so a control that keeps firing between
takes reads as the key that is still pressed. release lets go of that whole
set in one call, which is how a take starts from rest.
For the gamepad, pad takes the device name, which decides the legends a
prompt draws:
pad takes that device name, padPress a face or shoulder button by
compass name (south, east, ...), and padStick a stick, its x and y, and
how long to hold it. A wheel, pedals or a flight stick is connected with its
element counts, pad with { axes = 6, buttons = 25 }, and driven by
index with padDeviceAxis and padDeviceButton. Its axes start at 0
unless rest says where they rest: { axes = 3, rest = -1 } is a pedal box
with every pedal released. Connected with force = true, it plays
force-feedback effects, and Zin.gamepad.get(slot).force / .rumble read
back what a game played on it.
Why a control did not fire
A control can be live, its device can be producing input this frame, and the
game can still receive nothing. Zin.observe answers why in one call:
local Zin = require("@builtin::modules.zinput")
Zin.observe.whySilent("look")
--> { reason = "gateRefused", map = "default",
-- means = "the control's own gate answered no. A look control gates on
-- the player steering, so a cursor crossing the window reads
-- nothing.", kind = "axis2", subscribers = 1, ... }
The answer is one name from a closed set, and Zin.observe.reasons() lists
the set with a sentence each:
noMapActive · unknownControl · groupSuppressed · contextInactive ·
heldOnArrival · pointerTakenByUi · keyboardTakenByUi · padTakenByUi · gateErrored · gateRefused · noBindingForDevice ·
belowDeadzone · noSubscriber · atRest · delivering
atRest and unknownControl are the pair no value reader can separate: a
misspelled name and a control nobody is touching both read 0.
Zin.observe.control(name) puts everything about one control in a single
call — which maps contribute it, its bindings per device class, its
subscriber count, what it reported on the last tick, and why. Zin.observe .frame() is the whole tick: every live map, every control with what it did
and why, and what the tick cost. Both report one tick — the most recent
one — and reading takes nothing away from the next reader, so two observers
in the same frame both get the truth.
The binding layer's own per-frame cost lands in
profiler.stats("*zin.scheme.advance*") as script.zin.scheme.advance.
Reading the input layer without running a script
/runtime/input serves the same answers as a file, beside the engine's own
account of the frame's device events:
vfs.read("/zero/runtime/input") -- the whole document
vfs.read("/zero/runtime/input/events") -- events, each with consumed_by_ui
vfs.read("/zero/runtime/input/device") -- pointer lock, UI focus, devices
vfs.read("/zero/runtime/input/mapping") -- the mapping layer's tick
vfs.read("/zero/runtime/input/controls/look") -- one control's entry
input.observe() returns the same document to a script. Every device event
carries consumed_by_ui — whether the UI layer took THAT event, judged
against the focus the UI holds over the surface it arrived on, so a key
typed while the cursor merely hovers a panel is told from a key typed into a
text field. A key pressed after a click on an editor panel is the editor's
(see "Whose keys the scene holds" below) and carries consumed_by_ui too.
It is the same value a Zin.input.on* or Zin.events.on handler receives
as its second gpe argument.
The mapping half of the document costs a frame of work to build, so it is
built only while something is reading. A read arms it for a window of
frames; the document's mappingStatus says whether what it carries is
current, stale, arming (this read armed it — read again), or
unarmed. A read taken from a script during frame N answers for frame N-1,
since the engine publishes at the end of a frame.
Raw state
Zin.state.keyDown and friends read the per-frame snapshot beneath the
binding layer — the layer rebind capture and editor tooling operate on.
Polling it from gameplay makes that code keyboard-only, and draws the
engine-raw-key-poll diagnostic at author time.
Whose keys the scene holds
In the editor the scene shares the window with panels, and a key belongs to
the surface it was pressed on — the way a pointer gesture belongs to where it
began. The scene holds the keys pressed while it was the active input
context: the last click landed in the viewport's picture, the pointer is
locked to it, or play just started. The game's own screens are drawn in that
picture, so a click on one of their buttons (a Start or Restart button) is a
click in the game: the button takes the click and the scene holds the keys
typed next. A key pressed after a click on a panel is the editor's
for as long as it is held: no scene-surface map, Zin.state.keyDown poll or
event handler sees it, even once the context is back on the scene. A game
running with no editor around it is the whole window, and every key is its.
A focused widget takes only the keys it does something with. A text field
with the caret, a terminal and a widget with its own onKey take every key;
a focused button, checkbox or link takes Space and Enter, which press it; a
focused slider takes those and the arrows, Home, End, Page Up and Page Down,
which step it. Every other key reaches the game, so a menu button that kept
focus after Tab never stops the player walking with the arrows or WASD. The
snapshot states it each frame as keyboard_owner ("scene", "ui", or
"shared" with the taken keys in ui_keys), and a control those keys would
drive reports keyboardTakenByUi from Zin.observe.whySilent.
The editor's own maps declare surface = "editor" (see types/inputMap),
and editor code reads the same view with Zin.state.keyDown(code, "editor").
When the window loses focus, every key and button its keyboard and mouse
held is released, so nothing stays held while the author is in another app.
Text entry and pointer routing sit outside the control model on purpose: typing into a field and egui's pointer focus are not controls, and binding them would be wrong.