La référence API provient des commentaires de documentation Go du code source et est rédigée en anglais.
package input
import "github.com/nsgo-dev/game/pkg/input"Vue d’ensemble
Package input turns touch regions, mouse buttons, relative mouse motion under a pointer lock, keyboard keys, game controller buttons and sticks, and device motion sensors into named actions and axes sampled once per game.Loop step, saves bindings in core.Storage across launches, and plays haptic and rumble feedback.
Index
- Constantes
- type Actions
- func NewActions() *Actions
- func (a *Actions) ActionNames() []string
- func (a *Actions) Attach(v *core.View)
- func (a *Actions) AttachMotion(m *MotionInput)
- func (a *Actions) Axis(name string) float64
- func (a *Actions) AxisBinding(name string) (negative, positive string, ok bool)
- func (a *Actions) AxisNames() []string
- func (a *Actions) Bind(name string, inputs ...Input)
- func (a *Actions) BindAxis(name, negative, positive string)
- func (a *Actions) BindGamepadAxis(name string, axis gamepad.Axis, opts GamepadAxisOptions)
- func (a *Actions) BindMotionAxis(name string, axis MotionAxis, opts MotionAxisOptions)
- func (a *Actions) BindPointerAxis(name string, axis PointerAxis, opts PointerAxisOptions)
- func (a *Actions) BindVirtualPad(pad *VirtualPad)
- func (a *Actions) Bindings(name string) []Input
- func (a *Actions) CalibrateMotion()
- func (a *Actions) ClearAxis(name string)
- func (a *Actions) Delta(name string) float64
- func (a *Actions) GamepadAxisBinding(name string) (gamepad.Axis, GamepadAxisOptions, bool)
- func (a *Actions) Gamepads() []gamepad.Pad
- func (a *Actions) JustPressed(name string) bool
- func (a *Actions) JustReleased(name string) bool
- func (a *Actions) Load(store core.Storage, key string) (bool, error)
- func (a *Actions) LockPointer(cx *core.Scope, ref *core.Ref) bool
- func (a *Actions) Motion() *MotionInput
- func (a *Actions) MotionAxisBinding(name string) (MotionAxis, MotionAxisOptions, bool)
- func (a *Actions) OnContextMenu(ev core.ContextMenuEvent)
- func (a *Actions) OnGamepads(pads []gamepad.Pad)
- func (a *Actions) OnKeyDown(ev core.KeyEvent) bool
- func (a *Actions) OnKeyUp(ev core.KeyEvent)
- func (a *Actions) OnMotion(sample core.MotionSample)
- func (a *Actions) OnMouseLeave(ev core.MouseEvent)
- func (a *Actions) OnMouseMove(ev core.MouseEvent)
- func (a *Actions) OnPointerDelta(dx, dy float64)
- func (a *Actions) OnPressDown(ev core.PressEvent)
- func (a *Actions) OnPressUp(ev core.PressEvent)
- func (a *Actions) OnTouch(ev core.TouchEvent)
- func (a *Actions) PointerAxisBinding(name string) (PointerAxis, PointerAxisOptions, bool)
- func (a *Actions) PointerDelta() (dx, dy float64)
- func (a *Actions) PointerLockRequested() bool
- func (a *Actions) Press(name string)
- func (a *Actions) Pressed(name string) bool
- func (a *Actions) Release(name string)
- func (a *Actions) Reset()
- func (a *Actions) ResetMotionCalibration()
- func (a *Actions) Save(store core.Storage, key string) error
- func (a *Actions) SelectAnyGamepad()
- func (a *Actions) SelectGamepad(id int)
- func (a *Actions) SelectedGamepad() (id int, ok bool)
- func (a *Actions) SetAxis(name string, value float64)
- func (a *Actions) Step()
- func (a *Actions) Trigger(name string)
- func (a *Actions) Unbind(name string)
- func (a *Actions) UnbindAxis(name string)
- func (a *Actions) UnbindGamepadAxis(name string)
- func (a *Actions) UnbindMotionAxis(name string)
- func (a *Actions) UnbindPointerAxis(name string)
- func (a *Actions) UnbindVirtualPad(pad *VirtualPad)
- func (a *Actions) UnlockPointer()
- func (a *Actions) WatchGamepads(cx *core.Scope)
- func (a *Actions) WatchKeys(cx *core.Scope) (stop func())
- func (a *Actions) WatchMotion(cx *core.Scope, opts MotionOptions) (*MotionInput, error)
- type DeviceKind
- type DeviceTracker
- func NewDeviceTracker(cx *core.Scope, initial DeviceKind) *DeviceTracker
- func (t *DeviceTracker) Attach(v *core.View)
- func (t *DeviceTracker) LastDevice() DeviceKind
- func (t *DeviceTracker) LastDeviceUntracked() DeviceKind
- func (t *DeviceTracker) OnChange(fn func(DeviceKind))
- func (t *DeviceTracker) OnContextMenu(core.ContextMenuEvent)
- func (t *DeviceTracker) OnGamepad(kind DeviceKind)
- func (t *DeviceTracker) OnGamepadActivity(controllerName string)
- func (t *DeviceTracker) OnKey(core.KeyEvent)
- func (t *DeviceTracker) OnMouseMove(core.MouseEvent)
- func (t *DeviceTracker) OnPressDown(ev core.PressEvent)
- func (t *DeviceTracker) OnTouch(ev core.TouchEvent)
- func (t *DeviceTracker) OnWheel(core.WheelEvent)
- func (t *DeviceTracker) Reset()
- func (t *DeviceTracker) SetDevice(d DeviceKind)
- func (t *DeviceTracker) Signal() *core.Signal[DeviceKind]
- type DisconnectEvent
- type DisconnectPolicy
- type GamepadAxisOptions
- type GestureConfig
- type GestureEvent
- type GestureKind
- type GestureRecognizer
- func NewGestureRecognizer(a *Actions) *GestureRecognizer
- func (g *GestureRecognizer) Attach(v *core.View)
- func (g *GestureRecognizer) BindActions(a *Actions)
- func (g *GestureRecognizer) BindGesture(action string, kind GestureKind)
- func (g *GestureRecognizer) Events() []GestureEvent
- func (g *GestureRecognizer) OnTouch(ev core.TouchEvent)
- func (g *GestureRecognizer) PinchScale() float64
- func (g *GestureRecognizer) Reset()
- func (g *GestureRecognizer) Triggered(kind GestureKind) bool
- func (g *GestureRecognizer) UnbindGesture(action string)
- func (g *GestureRecognizer) Update(dt time.Duration)
- type Haptics
- func NewHaptics(cx *core.Scope) *Haptics
- func (h *Haptics) Error()
- func (h *Haptics) Heavy()
- func (h *Haptics) Light()
- func (h *Haptics) Load(store core.Storage, key string) (bool, error)
- func (h *Haptics) Medium()
- func (h *Haptics) Play(kind core.Haptic)
- func (h *Haptics) PlayPattern(steps ...RumbleStep)
- func (h *Haptics) Rigid()
- func (h *Haptics) Rumble(lowFreq, highFreq float32, duration time.Duration)
- func (h *Haptics) Rumbling() bool
- func (h *Haptics) Save(store core.Storage, key string) error
- func (h *Haptics) Selection()
- func (h *Haptics) SetEnabled(enabled bool)
- func (h *Haptics) Soft()
- func (h *Haptics) StopRumble()
- func (h *Haptics) Success()
- func (h *Haptics) Update(dt time.Duration)
- func (h *Haptics) Warning()
- type Input
- type InputKind
- type MotionAxis
- type MotionAxisOptions
- type MotionInput
- func NewMotionInput(opts MotionOptions) *MotionInput
- func WatchMotion(cx *core.Scope, opts MotionOptions) (*MotionInput, error)
- func (m *MotionInput) Active() bool
- func (m *MotionInput) Axis(axis MotionAxis) float64
- func (m *MotionInput) AxisWith(axis MotionAxis, opts MotionAxisOptions) float64
- func (m *MotionInput) Calibrate()
- func (m *MotionInput) Calibrated() bool
- func (m *MotionInput) Calibration() core.SensorVector
- func (m *MotionInput) OnMotion(sample core.MotionSample)
- func (m *MotionInput) Options() MotionOptions
- func (m *MotionInput) Reset()
- func (m *MotionInput) ResetCalibration()
- func (m *MotionInput) SetOptions(opts MotionOptions)
- func (m *MotionInput) Start(cx *core.Scope) error
- func (m *MotionInput) Step()
- func (m *MotionInput) Stop()
- type MotionOptions
- type Player
- func (p *Player) Actions() *Actions
- func (p *Player) Axis(name string) float64
- func (p *Player) Delta(name string) float64
- func (p *Player) FallbackActive() bool
- func (p *Player) Gamepad() (gamepad.Pad, bool)
- func (p *Player) GamepadConnected() bool
- func (p *Player) GamepadDisconnected() bool
- func (p *Player) GamepadID() (id int, ok bool)
- func (p *Player) HasDevice() bool
- func (p *Player) Index() int
- func (p *Player) JustPressed(name string) bool
- func (p *Player) JustReleased(name string) bool
- func (p *Player) Pressed(name string) bool
- func (p *Player) UsesKeyboard() bool
- func (p *Player) UsesPointer() bool
- type Players
- func NewPlayers(count int) *Players
- func (m *Players) Add() *Player
- func (m *Players) All() []*Player
- func (m *Players) AssignGamepad(index, padID int) bool
- func (m *Players) AssignKeyboard(index int) bool
- func (m *Players) AssignPointer(index int) bool
- func (m *Players) AssignUnassignedGamepads() int
- func (m *Players) Attach(v *core.View)
- func (m *Players) DisconnectPolicy() DisconnectPolicy
- func (m *Players) DisconnectedPlayers() []*Player
- func (m *Players) Gamepads() []gamepad.Pad
- func (m *Players) Len() int
- func (m *Players) NextUnassigned() *Player
- func (m *Players) OnContextMenu(ev core.ContextMenuEvent)
- func (m *Players) OnGamepads(pads []gamepad.Pad)
- func (m *Players) OnKeyDown(ev core.KeyEvent) bool
- func (m *Players) OnKeyUp(ev core.KeyEvent)
- func (m *Players) OnMouseLeave(ev core.MouseEvent)
- func (m *Players) OnMouseMove(ev core.MouseEvent)
- func (m *Players) OnPointerDelta(dx, dy float64)
- func (m *Players) OnPressDown(ev core.PressEvent)
- func (m *Players) OnPressUp(ev core.PressEvent)
- func (m *Players) OnTouch(ev core.TouchEvent)
- func (m *Players) PausedByDisconnect() bool
- func (m *Players) Player(index int) *Player
- func (m *Players) PlayerByGamepad(padID int) *Player
- func (m *Players) PollGamepads()
- func (m *Players) Reset()
- func (m *Players) SetDisconnectPolicy(policy DisconnectPolicy)
- func (m *Players) Step()
- func (m *Players) Unassign(index int) bool
- func (m *Players) UnassignGamepad(index int) bool
- func (m *Players) UnassignKeyboard(index int) bool
- func (m *Players) UnassignPointer(index int) bool
- func (m *Players) UnassignedGamepads() []gamepad.Pad
- func (m *Players) WatchGamepads(cx *core.Scope)
- func (m *Players) WatchKeys(cx *core.Scope) (stop func())
- type PointerAxis
- type PointerAxisOptions
- type Prompt
- type PromptTable
- func DefaultPromptTable() *PromptTable
- func NewPromptTable() *PromptTable
- func (t *PromptTable) Delete(action string, device DeviceKind)
- func (t *PromptTable) Lookup(action string, device DeviceKind) (Prompt, bool)
- func (t *PromptTable) Prompt(action string, device DeviceKind) Prompt
- func (t *PromptTable) PromptFor(action string, tracker *DeviceTracker) Prompt
- func (t *PromptTable) Set(action string, device DeviceKind, prompt Prompt)
- func (t *PromptTable) SetMany(action string, prompts map[DeviceKind]Prompt)
- type ReconnectEvent
- type RumbleStep
- type VirtualButton
- type VirtualPad
- func NewVirtualPad() *VirtualPad
- func (p *VirtualPad) AddButton(b *VirtualButton) *VirtualButton
- func (p *VirtualPad) AddStick(s *VirtualStick) *VirtualStick
- func (p *VirtualPad) Attach(v *core.View)
- func (p *VirtualPad) Axis(name string) float64
- func (p *VirtualPad) BindActions(a *Actions)
- func (p *VirtualPad) Draw(d *core.Drawing, style VirtualStyle)
- func (p *VirtualPad) OnTouch(ev core.TouchEvent)
- func (p *VirtualPad) Pressed(action string) bool
- func (p *VirtualPad) Reset()
- type VirtualStick
- type VirtualStyle
Constantes
const DefaultGamepadDeadZone = 0.15DefaultGamepadDeadZone is the stick dead zone GamepadAxisOptions uses when its DeadZone is 0: stick deflections up to this magnitude read 0.
Types
type Actions struct {
// MapPoint, when set, transforms a touch or mouse position from the view's coordinates before testing TouchRegion and MouseRegion bounds, such as mapping a view to a letterboxed virtual canvas. Returning false ignores the point for region tests.
MapPoint func(core.Point) (core.Point, bool)
// contains filtered or unexported fields
}Actions maps touch regions, mouse buttons, relative mouse motion under a pointer lock, keyboard keys and game controllers to named actions and axes, sampled once per fixed game.Loop step.
Call Attach on the game's view (or forward events to OnTouch, OnPressDown, OnPressUp, OnMouseMove, OnMouseLeave, OnContextMenu, OnPointerDelta, OnKeyDown and OnKeyUp), call WatchKeys to hear the keys held anywhere on the window, call WatchGamepads to read game controllers, and call Step at the start of each Loop.Update. Between steps, Pressed, JustPressed, JustReleased and Axis report that step's snapshot. A quick tap that starts and ends between two steps is latched so it still registers for one step.
The zero value is ready to use. Actions' methods are called on the engine's goroutine, as core.View's callbacks and Loop.Update are.
func (a *Actions) ActionNames() []stringActionNames returns the sorted names of all actions bound, referenced by axes or virtual pads, or currently active or injected on a.
func (a *Actions) Attach(v *core.View)Attach wires a's touch, press, mouse, context-menu, pointer-lock motion and key handlers onto v, chaining any callbacks already set on v. v hears keys only while it has the keyboard focus; WatchKeys hears them anywhere on the window. A key held as v leaves the tree stays held until Reset, as OnKeyUp says.
func (a *Actions) AttachMotion(m *MotionInput)AttachMotion connects m as the motion sample source for a's motion axes. Passing nil detaches any existing MotionInput without stopping it.
func (a *Actions) Axis(name string) float64Axis returns the value of name in [-1, 1] for the current step.
For an axis bound with BindAxis, its negative action contributes -1 and its positive action contributes +1. For an axis bound with BindMotionAxis, the calibrated and dead-zoned motion reading contributes a value in [-1, 1]. For an axis bound with BindPointerAxis, the step's scaled relative mouse motion contributes, as Delta reads it. For an axis bound with BindGamepadAxis, the dead-zoned stick reading of the controllers a reads contributes a value in [-1, 1]. An analog value from a VirtualPad stick bound to the same axis name is added too, as is any injected value set with SetAxis. When more than one is bound to the same axis name, their contributions are summed and clamped to [-1, 1]. Otherwise Axis returns 1 when action name is pressed and 0 when it is not.
func (a *Actions) AxisBinding(name string) (negative, positive string, ok bool)AxisBinding returns the negative and positive action names bound to axis name.
func (a *Actions) AxisNames() []stringAxisNames returns the sorted names of all axes bound or injected on a.
func (a *Actions) Bind(name string, inputs ...Input)Bind binds name to inputs, replacing any previous inputs for name. Calling Bind with no inputs unbinds name. A key name is lowercased, as Key does, so Bindings returns it lowercased.
func (a *Actions) BindAxis(name, negative, positive string)BindAxis binds axis name to two opposite actions: negative drives it toward -1 and positive toward +1. Calling BindAxis with two empty names unbinds the axis.
func (a *Actions) BindGamepadAxis(name string, axis gamepad.Axis, opts GamepadAxisOptions)BindGamepadAxis binds axis name to a stick axis of the game controllers a reads, mapped into [-1, 1] with opts' dead zone and sensitivity. An axis outside the W3C Standard Gamepad layout unbinds the gamepad axis for name.
A gamepad axis may share a name with an axis bound with BindAxis, BindMotionAxis or a VirtualPad stick; Actions.Axis sums all of them and clamps the result to [-1, 1].
func (a *Actions) BindMotionAxis(name string, axis MotionAxis, opts MotionAxisOptions)BindMotionAxis binds axis name on a to a tilt or gyroscope axis with opts. Calling BindMotionAxis with MotionAxisNone unbinds the motion axis for name. A motion axis may share a name with an opposite-action axis bound via BindAxis; Actions.Axis sums both contributions and clamps the result to [-1, 1].
func (a *Actions) BindPointerAxis(name string, axis PointerAxis, opts PointerAxisOptions)BindPointerAxis binds axis name on a to relative mouse motion along axis while the game holds the pointer lock, scaled by opts. Calling BindPointerAxis with PointerAxisNone unbinds the pointer axis for name.
Read the motion with Delta for mouselook, where a fast flick must turn the camera further than a slow one, or with Axis, which adds it to any other axis bound to name and clamps the sum to [-1, 1].
func (a *Actions) BindVirtualPad(pad *VirtualPad)BindVirtualPad connects pad to a so its virtual buttons drive their bound actions and its virtual sticks drive their named axes on each Step.
func (a *Actions) Bindings(name string) []InputBindings returns a copy of the inputs currently bound to name, or nil if name is unbound.
func (a *Actions) CalibrateMotion()CalibrateMotion captures the current tilt reading as the neutral hold angle on a's MotionInput.
func (a *Actions) ClearAxis(name string)ClearAxis removes an injected analog contribution previously set with SetAxis for axis name.
func (a *Actions) Delta(name string) float64Delta returns the relative motion of pointer axis name for the current step: the motion heard since the previous Step along its axis, scaled by Sensitivity and negated by Invert, without a clamp. It reads 0 when no pointer axis is bound to name.
func (a *Actions) GamepadAxisBinding(name string) (gamepad.Axis, GamepadAxisOptions, bool)GamepadAxisBinding returns the stick axis and options bound to name with BindGamepadAxis.
func (a *Actions) Gamepads() []gamepad.PadGamepads returns a copy of the controller state a last read, sorted by controller ID.
func (a *Actions) JustPressed(name string) boolJustPressed reports whether name became pressed on the current step and was not pressed on the previous step.
func (a *Actions) JustReleased(name string) boolJustReleased reports whether name was pressed on the previous step and is no longer pressed on the current step.
func (a *Actions) Load(store core.Storage, key string) (bool, error)Load replaces a's action and axis bindings with those saved in store under key, and reports whether key was present.
When key is absent, Load leaves a's existing bindings as they are and returns false, nil. When the stored value is invalid JSON, has a field Load does not know or uses an unknown format, Load leaves a's bindings untouched and returns false and an error: a *loaderr.Error that names key as its file, with the line and field of the problem and how to fix it.
func (a *Actions) LockPointer(cx *core.Scope, ref *core.Ref) boolLockPointer asks the platform to hide the pointer and keep it in place while the view ref names hears relative motion, which Attach forwards to a's pointer axes. It reports whether it made the request: false with a nil scope or ref, a view that has been removed, or a surface without the lock, as cx.Env().CanLockPointer reports. NSGo may still decline a request for a view that is not placed in the tree, such as one inside a held subtree, without telling the app.
Call it from every press on that view, whether or not a lock was requested before: browsers lock only during a user gesture, and locking again replaces the previous lock. Escape, the window losing focus and hiding or removing the view release the lock as the platform decides, and NSGo does not tell the app, so the next press is the way to resume.
func (a *Actions) Motion() *MotionInputMotion returns the MotionInput currently attached to a, or nil if none is attached.
func (a *Actions) MotionAxisBinding(name string) (MotionAxis, MotionAxisOptions, bool)MotionAxisBinding returns the motion axis and options bound to name.
func (a *Actions) OnContextMenu(ev core.ContextMenuEvent)OnContextMenu records a secondary (right) click from a view's OnContextMenu callback as a single-step pulse of core.MouseButtonRight at ev.Position.
func (a *Actions) OnGamepads(pads []gamepad.Pad)OnGamepads replaces the controller state a reads with pads, such as recorded or synthetic controllers in a unit test or an input replay, and latches any button that became pressed so it registers on the next Step even if it is released before then.
While WatchGamepads has a scope attached, the next Step replaces pads with the live controllers.
func (a *Actions) OnKeyDown(ev core.KeyEvent) boolOnKeyDown records a key going down from a view's OnKeyDown callback and reports whether an action is bound to it, which consumes the key so the keymap's bindings and the view's own Return and Space do not take it as well. A held key's auto-repeat changes nothing, and neither does the repeat of a key that went down before the view had the focus, whose coming up the view does not hear.
func (a *Actions) OnKeyUp(ev core.KeyEvent)OnKeyUp records a key coming up from a view's OnKeyUp callback. NSGo sends it for a key that went down while the view had the keyboard focus, wherever the focus has gone since, and for every key still held as the window loses the keyboard focus, so no key stays held. It does not send it once the view has left the tree, so a key held as the attached view is removed stays held until Reset; call Reset when the game view is replaced, or use WatchKeys, which has no such view.
func (a *Actions) OnMotion(sample core.MotionSample)OnMotion feeds a core.MotionSample directly into a's attached MotionInput (creating one lazily if none is attached). Useful for deterministic unit tests and input replays.
func (a *Actions) OnMouseLeave(ev core.MouseEvent)OnMouseLeave clears held mouse buttons when the pointer leaves the view.
func (a *Actions) OnMouseMove(ev core.MouseEvent)OnMouseMove records mouse movement and any held button from a view's OnMouseMove callback.
func (a *Actions) OnPointerDelta(dx, dy float64)OnPointerDelta records relative motion, right and down, from a view's OnPointerDelta callback, which NSGo calls only while that view holds the pointer lock. Motion adds up until the next Step; a value that is not finite is ignored.
func (a *Actions) OnPressDown(ev core.PressEvent)OnPressDown records a primary pointer press from a view's OnPressDown callback. Keyboard presses and presses synthesized while a touch finger is active are ignored so touches only trigger TouchRegion bindings.
func (a *Actions) OnPressUp(ev core.PressEvent)OnPressUp records a primary pointer release from a view's OnPressUp callback.
func (a *Actions) OnTouch(ev core.TouchEvent)OnTouch records a touch event from a view's OnTouch callback.
func (a *Actions) PointerAxisBinding(name string) (PointerAxis, PointerAxisOptions, bool)PointerAxisBinding returns the pointer axis and options bound to name.
func (a *Actions) PointerDelta() (dx, dy float64)PointerDelta returns the relative mouse motion, right and down, heard between the previous Step and the current one, unscaled.
func (a *Actions) PointerLockRequested() boolPointerLockRequested reports whether a holds a request from LockPointer that UnlockPointer has not released. It is not the platform's lock state: Escape, the window losing focus and hiding the view release the lock without NSGo telling the app, and the request stays. Do not use it to decide whether to call LockPointer again or whether the player is still looking around.
NSGo reports the release to its core (driver.EventPointerUnlocked) but exposes no callback or query to apps, so this package cannot report the real state (nsgo-dev/nsgo#2249).
func (a *Actions) Press(name string)Press holds action name pressed across subsequent Step calls until Release or Reset is called, even if name has no physical Input bindings. Like physical input, a Press followed by Release between two Step calls is latched so it still registers for one step.
func (a *Actions) Pressed(name string) boolPressed reports whether name is held during the current step.
func (a *Actions) Release(name string)Release ends an injected hold started by Press for action name.
func (a *Actions) Reset()Reset clears active touches, held mouse buttons, held keys, the last game controller state read, pending latches, motion readings, relative mouse motion and the current step snapshot, keeping all action, axis and calibration settings and any pointer lock, so mouselook survives a scene change; a game controller button held across Reset stays inactive until it is released, as a held mouse button does. UnlockPointer releases the lock. Call it on focus loss, backgrounding or a scene change so no action stays stuck.
func (a *Actions) ResetMotionCalibration()ResetMotionCalibration clears any neutral tilt offset on a's MotionInput.
func (a *Actions) Save(store core.Storage, key string) errorSave writes all of a's action, axis, motion axis, pointer axis and game controller stick axis bindings as JSON into store under key. It fails with *core.StorageFullError when the storage is full.
func (a *Actions) SelectAnyGamepad()SelectAnyGamepad makes a read every connected controller again: a button is pressed when it is pressed on any of them, and a stick axis takes the reading farthest from center.
func (a *Actions) SelectGamepad(id int)SelectGamepad makes a read only the controller with ID id, such as one player's controller in a local multiplayer game with one Actions per player. By default a reads every connected controller.
func (a *Actions) SelectedGamepad() (id int, ok bool)SelectedGamepad returns the controller ID chosen with SelectGamepad, and false when a reads every controller.
func (a *Actions) SetAxis(name string, value float64)SetAxis sets an injected analog contribution in [-1, 1] for axis name, sampled on each subsequent Step until ClearAxis or Reset is called. Non-finite (NaN) values are ignored; values outside [-1, 1] are clamped.
func (a *Actions) Step()Step samples the current input state into the step snapshot. Call it once at the start of each game.Loop.Update step.
func (a *Actions) Trigger(name string)Trigger latches action name so it registers as pressed on the next Step call, even if name has no physical Input bindings.
func (a *Actions) Unbind(name string)Unbind removes all inputs bound to name.
func (a *Actions) UnbindAxis(name string)UnbindAxis removes the axis binding for name.
func (a *Actions) UnbindGamepadAxis(name string)UnbindGamepadAxis removes the gamepad axis binding for name.
func (a *Actions) UnbindMotionAxis(name string)UnbindMotionAxis removes the motion axis binding for name.
func (a *Actions) UnbindPointerAxis(name string)UnbindPointerAxis removes the pointer axis binding for name.
func (a *Actions) UnbindVirtualPad(pad *VirtualPad)UnbindVirtualPad disconnects pad from a.
func (a *Actions) UnlockPointer()UnlockPointer releases a lock LockPointer requested, so the platform shows the pointer again where it was. Motion heard before the release still reaches the next Step. It does nothing when a holds no request, or when the platform has already released the lock.
func (a *Actions) WatchGamepads(cx *core.Scope)WatchGamepads makes a read the game controllers connected to cx's app on every Step with gamepad.Pads, so GamepadButton inputs and BindGamepadAxis axes follow the physical controllers on every target that supports them.
Step reads the controllers' state as of the current display frame, so call Step from game.Loop.Update as usual. A press and release that both happen between two Step calls are not seen. Reading stops once cx is disposed, and while cx's core.Access refuses core.AccessGamepad no controller is read. Passing nil stops reading and releases every controller input.
func (a *Actions) WatchKeys(cx *core.Scope) (stop func())WatchKeys has a hear the keys held anywhere on cx's window, whichever view has the keyboard focus, until cx is disposed or stop is called, which releases the keys it heard. A key held as Reset is called counts as released until it comes up and goes down again, as it does for a focused view. It follows core.KeysDown and core.KeyCodesDown, so keys typed into a text input or composed by an input method are never held, and every held key comes up as the window loses the keyboard focus. Call it once, from the scope that runs the game.Loop.
func (a *Actions) WatchMotion(cx *core.Scope, opts MotionOptions) (*MotionInput, error)WatchMotion creates a MotionInput with opts, starts watching device motion sensors on cx, attaches it to a, and returns it. Any previously attached stream on a's internal MotionInput is replaced (not stopped if owned externally). The new stream stops automatically when cx is disposed.
type DeviceKind uint8DeviceKind identifies the input device class the player last used.
const (
DeviceUnknown DeviceKind = iota
DeviceTouch
DeviceMouse
DeviceKeyboard
DeviceGamepadXbox
DeviceGamepadPlayStation
DeviceGamepadNintendo
DeviceGamepadGeneric
)func DetectGamepadKind(name string) DeviceKindDetectGamepadKind infers the gamepad brand from a controller name string, falling back to DeviceGamepadGeneric.
func (d DeviceKind) IsGamepad() boolIsGamepad reports whether d is one of the gamepad device kinds.
func (d DeviceKind) String() stringString returns a short canonical name for d.
type DeviceTracker struct {
// contains filtered or unexported fields
}DeviceTracker tracks the player's last-used input device across touch, mouse, keyboard, and gamepad activity.
When constructed with NewDeviceTracker(cx, initial) and a non-nil core.Scope, it backs LastDevice with a core.Signal[DeviceKind] so reactive HUD views automatically re-render whenever the player switches devices.
The zero value is ready to use in non-reactive mode starting at DeviceUnknown.
func NewDeviceTracker(cx *core.Scope, initial DeviceKind) *DeviceTrackerNewDeviceTracker returns a DeviceTracker initialized to initial. When cx is non-nil, it creates a reactive core.Signal[DeviceKind] owned by cx.
func (t *DeviceTracker) Attach(v *core.View)Attach wires t's touch, mouse, press, wheel, and keyboard handlers onto v, chaining any existing callbacks without consuming key events.
func (t *DeviceTracker) LastDevice() DeviceKindLastDevice returns the most recently used input device. When t was created with a core.Scope, reading LastDevice subscribes the current reactive computation to device changes.
func (t *DeviceTracker) LastDeviceUntracked() DeviceKindLastDeviceUntracked returns the most recently used input device without subscribing to t's signal.
func (t *DeviceTracker) OnChange(fn func(DeviceKind))OnChange registers fn to run whenever the tracked device changes.
func (t *DeviceTracker) OnContextMenu(core.ContextMenuEvent)OnContextMenu records a secondary mouse click and switches to DeviceMouse.
func (t *DeviceTracker) OnGamepad(kind DeviceKind)OnGamepad records gamepad activity for kind. Non-gamepad kinds default to DeviceGamepadGeneric.
func (t *DeviceTracker) OnGamepadActivity(controllerName string)OnGamepadActivity records gamepad activity using a controller name string to infer its brand.
func (t *DeviceTracker) OnKey(core.KeyEvent)OnKey records hardware keyboard activity and switches to DeviceKeyboard.
func (t *DeviceTracker) OnMouseMove(core.MouseEvent)OnMouseMove records mouse pointer movement and switches the active device to DeviceMouse.
func (t *DeviceTracker) OnPressDown(ev core.PressEvent)OnPressDown records a press event. Keyboard presses switch to DeviceKeyboard; pointer presses switch to DeviceMouse unless synthesized while a touch finger is active.
func (t *DeviceTracker) OnTouch(ev core.TouchEvent)OnTouch records touch activity and switches the active device to DeviceTouch.
func (t *DeviceTracker) OnWheel(core.WheelEvent)OnWheel records mouse wheel activity and switches to DeviceMouse.
func (t *DeviceTracker) Reset()Reset clears active touch tracking while keeping the last-used device.
func (t *DeviceTracker) SetDevice(d DeviceKind)SetDevice explicitly sets the last-used device and notifies subscribers if it changed.
func (t *DeviceTracker) Signal() *core.Signal[DeviceKind]Signal returns the reactive signal backing t, or nil if t was created without a core.Scope.
type DisconnectEvent struct {
// PlayerIndex is the 0-based index of the affected player slot.
PlayerIndex int
// Player is the affected player slot.
Player *Player
// PreviousGamepadID is the controller ID that disconnected.
PreviousGamepadID int
// FallbackActive reports whether FallbackToKeyboardTouch enabled keyboard and pointer fallback for this player instead of pausing.
FallbackActive bool
// ShouldPause reports whether the policy requests pausing gameplay for this disconnect.
ShouldPause bool
}DisconnectEvent describes a player's assigned game controller disconnecting mid-game.
type DisconnectPolicy struct {
// PauseOnDisconnect requests a pause (via OnPause) whenever at least one player's assigned controller disconnects without an active keyboard/pointer fallback, and requests resume once every disconnected player that caused the pause has recovered or been unassigned.
PauseOnDisconnect bool
// AllowReassignOnPress lets an unassigned connected controller claim the lowest-index player slot awaiting reconnect when a button is newly pressed on that controller.
AllowReassignOnPress bool
// FallbackToKeyboardTouch lets a player whose assigned controller disconnects continue playing via keyboard and pointer/touch without pausing. Players temporarily enables keyboard and pointer routing on that player until a controller reconnects or claims the slot, then restores the player's prior keyboard and pointer assignments.
FallbackToKeyboardTouch bool
// OnPause, when set, is called with true when PauseOnDisconnect pauses gameplay and with false once every disconnected required player has recovered or been unassigned. Pass game.Loop.SetPaused directly to pause and resume a Loop.
OnPause func(paused bool)
// OnDisconnect, when set, is called when a player's previously connected assigned controller disappears from the controller snapshot.
OnDisconnect func(DisconnectEvent)
// OnReconnect, when set, is called when a player awaiting reconnect regains its previous controller or is reassigned to another connected controller (automatically via AllowReassignOnPress or manually via AssignGamepad).
OnReconnect func(ReconnectEvent)
}DisconnectPolicy configures how Players responds when a player's assigned game controller disconnects mid-game and how that player recovers.
type GamepadAxisOptions struct {
// DeadZone is the stick deflection in [0, 1) below which the axis reads 0; readings beyond it are rescaled so the axis still rises smoothly from 0 to 1. Zero uses DefaultGamepadDeadZone, and a negative value turns the dead zone off.
DeadZone float64
// Axial applies DeadZone to this axis alone instead of to the whole stick. By default the dead zone is radial: it measures the stick's distance from center over both of its axes, so a diagonal push is not snapped to a straight line.
Axial bool
// Sensitivity multiplies the dead-zoned value before clamping to [-1, 1] (1 when <= 0).
Sensitivity float64
// Invert negates the resulting axis value, such as to make pushing the stick up read positive on AxisLeftY.
Invert bool
}GamepadAxisOptions configures how one bound stick axis is mapped into [-1, 1].
type GestureConfig struct {
// TapMaxDuration is the maximum press duration for GestureTap.
TapMaxDuration time.Duration
// TapMaxDistance is the maximum finger drift in points allowed for GestureTap and GestureLongPress.
TapMaxDistance float32
// DoubleTapMaxInterval is the maximum elapsed time between two taps to recognize GestureDoubleTap.
DoubleTapMaxInterval time.Duration
// DoubleTapMaxDistance is the maximum distance in points between two taps to recognize GestureDoubleTap.
DoubleTapMaxDistance float32
// LongPressDuration is how long a stationary finger must be held to fire GestureLongPress.
LongPressDuration time.Duration
// SwipeMinDistance is the minimum drag distance in points for a directional swipe.
SwipeMinDistance float32
// SwipeMinVelocity is the minimum drag speed in points per second for a directional swipe.
SwipeMinVelocity float32
// PinchMinDelta is the minimum change in two-finger spacing in points to fire GesturePinchIn or GesturePinchOut.
PinchMinDelta float32
}GestureConfig tunes the thresholds used by GestureRecognizer.
Any non-positive field falls back to DefaultGestureConfig.
func DefaultGestureConfig() GestureConfigDefaultGestureConfig returns balanced mobile/tablet thresholds for GestureRecognizer.
type GestureEvent struct {
Kind GestureKind
Position core.Point
// Scale is the current pinch ratio (currentDistance / initialDistance) for GesturePinchIn and GesturePinchOut, and 0 for non-pinch gestures.
Scale float64
}GestureEvent describes a single gesture recognized on a simulation step.
type GestureKind uint8GestureKind identifies a touch gesture recognized by GestureRecognizer.
const (
GestureNone GestureKind = iota
GestureTap
GestureDoubleTap
GestureLongPress
GestureSwipeLeft
GestureSwipeRight
GestureSwipeUp
GestureSwipeDown
GesturePinchIn
GesturePinchOut
)func (g GestureKind) String() stringString returns a human-readable name for g.
type GestureRecognizer struct {
// Config overrides default gesture thresholds. Zero fields use DefaultGestureConfig.
Config GestureConfig
// MapPoint, when set, transforms touch points from view coordinates before gesture recognition. Returning false ignores the point.
MapPoint func(core.Point) (core.Point, bool)
// OnGesture, when set, runs during Update for each gesture recognized on that step.
OnGesture func(GestureEvent)
// contains filtered or unexported fields
}GestureRecognizer deterministically recognizes taps, double-taps, long-presses, four-direction swipes, and two-finger pinches from core.TouchEvent streams stepped by game.Loop's Update(dt).
Call OnTouch from the view (or Attach to wire it) and call Update(dt) once per game.Loop.Update step before Actions.Step so gesture-bound actions trigger on that exact step.
The zero value is ready to use.
func NewGestureRecognizer(a *Actions) *GestureRecognizerNewGestureRecognizer returns a GestureRecognizer optionally wired to trigger actions on a.
func (g *GestureRecognizer) Attach(v *core.View)Attach wires g.OnTouch onto v, chaining any existing v.OnTouch callback.
func (g *GestureRecognizer) BindActions(a *Actions)BindActions wires g to trigger bound actions on a (or disconnects when a is nil).
func (g *GestureRecognizer) BindGesture(action string, kind GestureKind)BindGesture binds action to gesture kind. When kind is recognized, g triggers action on its bound Actions. Binding GestureNone removes action's gesture bindings.
func (g *GestureRecognizer) Events() []GestureEventEvents returns a copy of all gestures recognized on the most recent Update step.
func (g *GestureRecognizer) OnTouch(ev core.TouchEvent)OnTouch records touch activity for gesture recognition.
func (g *GestureRecognizer) PinchScale() float64PinchScale returns the current two-finger pinch scale ratio (currentDistance / initialDistance), or 1 when no pinch is active.
func (g *GestureRecognizer) Reset()Reset clears active touches, pinch state, pending tap history, and the current step's events while keeping Config, MapPoint, OnGesture, and gesture bindings.
func (g *GestureRecognizer) Triggered(kind GestureKind) boolTriggered reports whether kind fired on the most recent Update step.
func (g *GestureRecognizer) UnbindGesture(action string)UnbindGesture removes all gesture bindings for action.
func (g *GestureRecognizer) Update(dt time.Duration)Update advances the deterministic gesture clock by dt, evaluates held long-presses, promotes pending touch gestures into the current step, and triggers any bound Actions.
type Haptics struct {
// Enabled controls whether any haptic or rumble feedback is emitted (true by default).
// Set to false for accessibility or player preferences.
Enabled bool
// PulseInterval is how frequently mobile haptic pulses repeat during a continuous Rumble
// (50 ms when <= 0).
PulseInterval time.Duration
// GamepadRumble, when set, receives motor strength updates for external gamepad rumble
// backends (seam for nsgo#1049). Called with (lowFreq, highFreq, duration) in [0, 1]
// when a rumble segment begins, and with (0, 0, 0) when rumble finishes, stops, is disabled,
// or pauses in background.
GamepadRumble func(lowFreq, highFreq float32, duration time.Duration)
// OnHaptic, when set, is called each time a haptic is dispatched to core.Scope.PlayHaptic.
// Useful for visual accessibility cues, telemetry, or tests.
OnHaptic func(core.Haptic)
// contains filtered or unexported fields
}Haptics plays tactile feedback through core.Scope.PlayHaptic on iOS and Android, runs timed rumble and multi-step patterns on Update(dt), and forwards motor updates to an optional GamepadRumble sink (a seam for gamepad rumble hardware).
All output is silenced while Enabled is false or while the scope's window is in core.LifecycleBackground. Any active rumble stops automatically when disabled, backgrounded, or when the owning scope is disposed.
Haptics' methods are called on the engine's goroutine, as core.Scope and game.Loop.Update are.
func NewHaptics(cx *core.Scope) *HapticsNewHaptics returns a Haptics bound to cx with Enabled set to true. It watches cx's lifecycle so feedback pauses cleanly in core.LifecycleBackground, and stops any active rumble when cx is disposed.
func (h *Haptics) Error()Error plays an error/failure outcome haptic (core.HapticError).
func (h *Haptics) Heavy()Heavy plays a heavy impact haptic (core.HapticHeavy).
func (h *Haptics) Light()Light plays a light impact haptic (core.HapticLight).
func (h *Haptics) Load(store core.Storage, key string) (bool, error)Load restores h.Enabled from store under key and reports whether key was present. When key is absent or invalid, h.Enabled is left untouched. An invalid value's error is a *loaderr.Error that names key as its file.
func (h *Haptics) Medium()Medium plays a medium impact haptic (core.HapticMedium).
func (h *Haptics) Play(kind core.Haptic)Play emits kind through core.Scope.PlayHaptic when h is enabled and in foreground. Invalid haptic values are ignored.
func (h *Haptics) PlayPattern(steps ...RumbleStep)PlayPattern runs a sequence of timed RumbleSteps, replacing any active rumble. Call Update(dt) on each game.Loop step to advance the pattern.
func (h *Haptics) Rigid()Rigid plays a rigid impact haptic (core.HapticRigid).
func (h *Haptics) Rumble(lowFreq, highFreq float32, duration time.Duration)Rumble starts a timed rumble with lowFreq and highFreq motor strengths in [0, 1] for duration. Calling Rumble with duration <= 0 or both strengths <= 0 stops any active rumble. Step the rumble scheduler by calling Update(dt) from game.Loop.Update.
func (h *Haptics) Rumbling() boolRumbling reports whether a rumble or pattern is currently playing.
func (h *Haptics) Save(store core.Storage, key string) errorSave writes h.Enabled into store under key. It fails with *core.StorageFullError when storage is full.
func (h *Haptics) Selection()Selection plays a subtle selection-change tick (core.HapticSelection).
func (h *Haptics) SetEnabled(enabled bool)SetEnabled sets h.Enabled and immediately stops any active rumble when disabling.
func (h *Haptics) Soft()Soft plays a soft impact haptic (core.HapticSoft).
func (h *Haptics) StopRumble()StopRumble immediately stops any active rumble or pattern and zeroes the gamepad motor sink.
func (h *Haptics) Success()Success plays a positive outcome haptic (core.HapticSuccess).
func (h *Haptics) Update(dt time.Duration)Update advances any active rumble or pattern by dt, emitting periodic mobile haptic pulses and ending or advancing steps as their durations expire. Call it from game.Loop.Update.
func (h *Haptics) Warning()Warning plays a warning outcome haptic (core.HapticWarning).
type Input struct {
Kind InputKind
Bounds core.Bounds
Button core.MouseButton
// Key is the key name of an InputKey, such as "a", "left", "space" or "shift".
Key string
// Code is the physical position of an InputKeyCode, such as "KeyW" or "ArrowLeft".
Code string
// PadButton is the controller button of an InputGamepadButton input.
PadButton gamepad.Button
}Input is one physical trigger bound to an action: a touch region, a mouse button, a mouse button in a region, a key, a key's physical position or a game controller button.
Make one with TouchRegion, MouseButton, MouseRegion, Key, KeyCode or GamepadButton. Its zero value is never active.
func GamepadButton(b gamepad.Button) InputGamepadButton returns an input that is active while button b is pressed (value at least 0.5, as gamepad.Pad.Pressed tests) on a connected game controller that a uses (see SelectGamepad). A button outside the W3C Standard Gamepad layout is never active.
Bind it with Actions.Bind like any other Input, and feed controller state to the Actions with WatchGamepads or OnGamepads.
func Key(name string) InputKey returns an input that is active while the key named name is held, named as core.KeyEvent.Key names it: "a", "1", "space", "enter", "left", "f5", or a modifier alone, "shift", "ctrl", "alt" or "meta". Only those names are held: the aliases core.KeyHeld also accepts, such as "mod", "cmd" or "option", never are, so bind "meta" where Env.AppleKeys reports Command as the platform modifier and "ctrl" elsewhere. A letter or a digit is the one the keyboard layout types unshifted, so Key follows the layout; KeyCode follows the physical position instead. The name is matched without regard to case, and an empty name is never active.
func KeyCode(code string) InputKeyCode returns an input that is active while the key at physical position code is held, named as core.KeyEvent.Code names it, after the web's KeyboardEvent.code: "KeyW", "ArrowLeft", "Space", "ShiftLeft". A position stays where it is on every layout, so KeyCode("KeyW") is the key above S on QWERTY and AZERTY alike. An empty code is never active.
func MouseButton(button core.MouseButton) InputMouseButton returns an input that is active while button is held down on the view. core.MouseButtonNone is never active.
func MouseRegion(rect core.Bounds, button core.MouseButton) InputMouseRegion returns an input that is active while button is held down and the mouse lies inside rect, as core.Bounds.Contains tests. core.MouseButtonNone is never active.
func TouchRegion(rect core.Bounds) InputTouchRegion returns an input that is active while any touch finger lies inside rect: from its origin, included, to its far edges, excluded, as core.Bounds.Contains tests.
type InputKind uint8InputKind says what kind of physical input an Input watches.
const (
// InputNone is the zero Input, which is never active.
InputNone InputKind = iota
// InputTouchRegion is active while any touch finger lies inside a rectangle.
InputTouchRegion
// InputMouseButton is active while a mouse button is held down on the view.
InputMouseButton
// InputMouseRegion is active while a mouse button is held down inside a rectangle.
InputMouseRegion
// InputKey is active while a keyboard key, named as core.KeyEvent.Key names it, is held.
InputKey
// InputKeyCode is active while a keyboard key at a physical position, named as core.KeyEvent.Code names it, is held.
InputKeyCode
// InputGamepadButton is active while a button is pressed on a game controller the Actions reads.
InputGamepadButton
)type MotionAxis uint8MotionAxis identifies one tilt (accelerometer/gravity) or gyroscope axis.
const (
// MotionAxisNone is the zero MotionAxis, which always reads 0.
MotionAxisNone MotionAxis = iota
// TiltX is device tilt along the natural device X axis (right, in g units).
TiltX
// TiltY is device tilt along the natural device Y axis (up, in g units).
TiltY
// TiltZ is device tilt along the natural device Z axis (out of the screen, in g units).
TiltZ
// GyroX is angular velocity around the natural device X axis (rad/s).
GyroX
// GyroY is angular velocity around the natural device Y axis (rad/s).
GyroY
// GyroZ is angular velocity around the natural device Z axis (rad/s).
GyroZ
)func (m MotionAxis) String() stringString returns a stable name for m.
type MotionAxisOptions struct {
// DeadZone is the magnitude in [0, 1) below which the axis reads 0.
DeadZone float64
// Sensitivity multiplies the calibrated reading before clamping.
Sensitivity float64
// MaxRange is the input magnitude that maps to 1.0 before Sensitivity:
// in g for Tilt axes (default 1.0), and in rad/s for Gyro axes (default math.Pi).
MaxRange float64
// Smoothing is an optional per-axis low-pass factor in [0, 1) applied on each Step.
Smoothing float64
// Invert negates the resulting axis value.
Invert bool
}MotionAxisOptions configures how one bound motion axis is mapped into [-1, 1]. Zero-valued DeadZone, Sensitivity and MaxRange inherit defaults from the attached MotionInput.
type MotionInput struct {
// contains filtered or unexported fields
}MotionInput watches device accelerometer and gyroscope sensors via core.Scope.WatchMotion, calibrates tilt against a neutral hold angle, applies low-pass smoothing, dead zone and sensitivity, and exposes [-1, 1] axis values sampled once per fixed game.Loop step.
MotionInput's methods are called on the engine's goroutine, as core.Scope.WatchMotion callbacks and game.Loop.Update are.
func NewMotionInput(opts MotionOptions) *MotionInputNewMotionInput returns a MotionInput configured with opts. Call Start(cx) to subscribe to live device sensors, or feed samples directly with OnMotion.
func WatchMotion(cx *core.Scope, opts MotionOptions) (*MotionInput, error)WatchMotion creates a MotionInput with opts and immediately subscribes to device motion sensors on cx via cx.WatchMotion. The sensor stream stops automatically when cx is disposed (or when Stop is called) and pauses automatically while the app is in background.
func (m *MotionInput) Active() boolActive reports whether m currently has a live, unstopped sensor stream.
func (m *MotionInput) Axis(axis MotionAxis) float64Axis returns the stepped value of axis in [-1, 1] using m's default options.
func (m *MotionInput) AxisWith(axis MotionAxis, opts MotionAxisOptions) float64AxisWith returns the stepped value of axis in [-1, 1] using per-axis opts, with zero fields falling back to m's defaults.
func (m *MotionInput) Calibrate()Calibrate captures the current tilt reading as the neutral hold orientation so TiltX, TiltY and TiltZ read 0 at that hold angle. If no tilt sample has arrived yet, the next tilt sample received is captured as the neutral orientation.
func (m *MotionInput) Calibrated() boolCalibrated reports whether a neutral tilt offset has been captured.
func (m *MotionInput) Calibration() core.SensorVectorCalibration returns the captured neutral tilt vector in g units.
func (m *MotionInput) OnMotion(sample core.MotionSample)OnMotion ingests one core.MotionSample (from WatchMotion, a unit test, or a replay). Updated values are held until the next Step call so reads stay stable within a fixed game.Loop step.
func (m *MotionInput) Options() MotionOptionsOptions returns m's current MotionOptions.
func (m *MotionInput) Reset()Reset clears live and snapped sensor readings without changing options, calibration or the active stream.
func (m *MotionInput) ResetCalibration()ResetCalibration clears any neutral tilt offset captured by Calibrate.
func (m *MotionInput) SetOptions(opts MotionOptions)SetOptions updates DeadZone, Sensitivity, TiltRange, GyroRange, Smoothing and OnError at runtime. Changing Sensors or Interval takes effect on the next Start call.
func (m *MotionInput) Start(cx *core.Scope) errorStart subscribes to live device motion sensors on cx using m's options. Any previously active stream on m is stopped first.
func (m *MotionInput) Step()Step snapshots the latest smoothed sensor readings for the current game.Loop step. Calling Step multiple times with no new samples in between is idempotent.
func (m *MotionInput) Stop()Stop cancels the active sensor stream, if any.
type MotionOptions struct {
// Sensors chooses which NSGo motion sensors to watch.
// Zero requests core.SensorAccelerometer | core.SensorGyroscope.
Sensors core.MotionSensors
// Interval is the requested sample interval, clamped by NSGo to 10ms..1s (0 defaults to 20ms).
Interval time.Duration
// DeadZone is the default magnitude in [0, 1) below which normalized axis readings snap to 0.
DeadZone float64
// Sensitivity multiplies calibrated axis values before clamping (1 when <= 0).
Sensitivity float64
// TiltRange is the tilt magnitude in g (9.80665 m/s²) that maps to 1.0 before Sensitivity (1.0 when <= 0).
TiltRange float64
// GyroRange is the rotation rate in rad/s that maps to 1.0 before Sensitivity (math.Pi when <= 0).
GyroRange float64
// Smoothing is the low-pass filter factor in [0, 1) applied to incoming samples.
// 0 disables smoothing; higher values smooth more heavily (filtered = prev*Smoothing + raw*(1-Smoothing)).
Smoothing float64
// OnError is called on the engine goroutine if WatchMotion's provider reports an error
// (such as core.SensorNotAllowed or core.SensorNotAvailable).
OnError func(error)
}MotionOptions configures a MotionInput watching device sensors via core.Scope.WatchMotion.
type Player struct {
// contains filtered or unexported fields
}Player is one player's input slot in a Players group, with its own Actions and assigned physical devices.
A nil *Player reports zero/false for all queries and -1 for Index.
func (p *Player) Actions() *ActionsActions returns p's Actions, where bindings, axes, virtual pads, and saved controls live. Returns nil if p is nil.
func (p *Player) Axis(name string) float64Axis returns the value of axis name in [-1, 1] for p on the current step.
func (p *Player) Delta(name string) float64Delta returns the relative motion of pointer axis name for p on the current step.
func (p *Player) FallbackActive() boolFallbackActive reports whether p is currently using temporary keyboard and pointer fallback because its assigned controller disconnected under DisconnectPolicy.FallbackToKeyboardTouch. Returns false if p is nil.
func (p *Player) Gamepad() (gamepad.Pad, bool)Gamepad returns the latest connected controller state for p's assigned controller, or false when p has no assigned controller or that controller is not currently connected.
func (p *Player) GamepadConnected() boolGamepadConnected reports whether p has an assigned controller that is present in the latest controller snapshot.
func (p *Player) GamepadDisconnected() boolGamepadDisconnected reports whether p has an assigned controller that was previously connected and has since disconnected, awaiting reconnect or reassignment. Returns false if p is nil.
func (p *Player) GamepadID() (id int, ok bool)GamepadID returns the controller ID assigned to p and true, or (0, false) when p has no assigned controller.
func (p *Player) HasDevice() boolHasDevice reports whether at least one physical device (a controller, keyboard, or pointer) is assigned to p.
func (p *Player) Index() intIndex returns p's 0-based slot index in its Players group, or -1 if p is nil.
func (p *Player) JustPressed(name string) boolJustPressed reports whether action name became pressed for p on the current step.
func (p *Player) JustReleased(name string) boolJustReleased reports whether action name was released for p on the current step.
func (p *Player) Pressed(name string) boolPressed reports whether action name is held for p during the current step.
func (p *Player) UsesKeyboard() boolUsesKeyboard reports whether keyboard events from p's Players group are routed to p.
func (p *Player) UsesPointer() boolUsesPointer reports whether touch, mouse, and pointer-lock events from p's Players group are routed to p.
type Players struct {
// contains filtered or unexported fields
}Players coordinates local multiplayer input across several player slots, routing each connected game controller to at most one player and sharing keyboard or pointer events among the players assigned to them, sampled once per fixed game.Loop step.
Each player owns its own Actions (accessed via Player.Actions), so several players can share the same gamepad bindings on separate controllers, use disjoint key sets on one keyboard, or combine keyboard, pointer, and game controllers.
Call WatchGamepads, WatchKeys, and/or Attach on Players rather than on individual players' Actions, assign devices with AssignGamepad, AssignKeyboard, AssignPointer, or AssignUnassignedGamepads, and call Step once at the start of each game.Loop.Update step.
The zero value is ready to use with no players; call NewPlayers or Add to create slots. Players' methods are called on the engine's goroutine, as core.View's callbacks and game.Loop.Update are.
func NewPlayers(count int) *PlayersNewPlayers returns a Players group with count player slots (0 to count-1), each with an empty Actions and no assigned devices. A non-positive count returns an empty Players.
func (m *Players) Add() *PlayerAdd appends a new player slot with an empty Actions and no assigned devices, and returns it.
func (m *Players) All() []*PlayerAll returns a copy of the player slots in index order, or nil when m has no players.
func (m *Players) AssignGamepad(index, padID int) boolAssignGamepad assigns controller padID exclusively to player index, returning false if index is out of range.
If another player already owns padID, that player is unassigned from padID first and its held controller inputs are released. If padID is not yet connected, the assignment is remembered and takes effect once padID appears in Step or OnGamepads. If player index was awaiting reconnect and padID is currently connected, AssignGamepad completes recovery, ends any active fallback, and emits OnReconnect.
func (m *Players) AssignKeyboard(index int) boolAssignKeyboard routes keyboard events from m (WatchKeys, OnKeyDown, OnKeyUp, Attach) to player index, returning false if index is out of range.
Multiple players may be assigned to the keyboard simultaneously so they can share one keyboard with disjoint key sets.
func (m *Players) AssignPointer(index int) boolAssignPointer routes touch, mouse, and pointer-lock events from m (Attach and OnTouch/OnPressDown/OnMouseMove/OnPointerDelta) to player index, returning false if index is out of range.
Multiple players may be assigned to pointer events, such as split-screen touch regions on one screen.
func (m *Players) AssignUnassignedGamepads() intAssignUnassignedGamepads assigns each connected controller from the last read (Step or OnGamepads) that is not yet assigned to any player, in ascending controller ID order, to the next player slot that has no device assigned, and returns how many controllers were assigned.
func (m *Players) Attach(v *core.View)Attach wires m's touch, press, mouse, context-menu, pointer-lock motion, and key handlers onto v, chaining any callbacks already set on v. Keyboard events are forwarded to players with AssignKeyboard; pointer and touch events are forwarded to players with AssignPointer.
func (m *Players) DisconnectPolicy() DisconnectPolicyDisconnectPolicy returns the disconnect and reconnect policy currently configured on m.
func (m *Players) DisconnectedPlayers() []*PlayerDisconnectedPlayers returns the player slots currently awaiting controller reconnect, in ascending slot index order, or nil if no player is disconnected.
func (m *Players) Gamepads() []gamepad.PadGamepads returns a copy of the controller state m last read, sorted by controller ID.
func (m *Players) NextUnassigned() *PlayerNextUnassigned returns the first player slot with no device assigned, or nil when every slot has a device.
func (m *Players) OnContextMenu(ev core.ContextMenuEvent)OnContextMenu forwards ev to every player assigned to pointer events.
func (m *Players) OnGamepads(pads []gamepad.Pad)OnGamepads replaces the controller state m reads with pads, such as synthetic or recorded controllers in a unit test or replay, routes each controller to its assigned player, processes any disconnect, reconnect, or press-to-reassign policy transitions, and latches any rising edges so a quick press between steps registers on the next Step.
While WatchGamepads has a live scope attached, the next Step replaces pads with the live controllers.
func (m *Players) OnKeyDown(ev core.KeyEvent) boolOnKeyDown forwards ev to every player assigned to the keyboard and reports whether any of them consumed it.
func (m *Players) OnKeyUp(ev core.KeyEvent)OnKeyUp forwards ev to every player assigned to the keyboard.
func (m *Players) OnMouseLeave(ev core.MouseEvent)OnMouseLeave forwards ev to every player assigned to pointer events.
func (m *Players) OnMouseMove(ev core.MouseEvent)OnMouseMove forwards ev to every player assigned to pointer events.
func (m *Players) OnPointerDelta(dx, dy float64)OnPointerDelta forwards relative pointer motion to every player assigned to pointer events.
func (m *Players) OnPressDown(ev core.PressEvent)OnPressDown forwards ev to every player assigned to pointer events.
func (m *Players) OnPressUp(ev core.PressEvent)OnPressUp forwards ev to every player assigned to pointer events.
func (m *Players) OnTouch(ev core.TouchEvent)OnTouch forwards ev to every player assigned to pointer events.
func (m *Players) PausedByDisconnect() boolPausedByDisconnect reports whether m has paused gameplay via DisconnectPolicy.PauseOnDisconnect because at least one disconnected player is awaiting a controller without fallback.
func (m *Players) Player(index int) *PlayerPlayer returns the player at slot index, or nil if index is out of range.
func (m *Players) PlayerByGamepad(padID int) *PlayerPlayerByGamepad returns the player currently assigned to controller padID, or nil if no player owns padID.
func (m *Players) PollGamepads()PollGamepads reads the live controllers once from the scope passed to WatchGamepads, processes any controller disconnect, reconnect, or press-to-reassign transitions, and updates each player's controller state without stepping Actions.
When WatchGamepads has a live scope and a DisconnectPolicy is configured, Players automatically polls on display frames while any player is awaiting reconnect so a paused game.Loop resumes once a controller reconnects or presses a button. Call PollGamepads directly if you drive polling outside game.Loop.
func (m *Players) Reset()Reset calls Reset on every player's Actions and clears m's last controller snapshot, keeping all player slots, bindings, and device assignments. Held keys and controller buttons stay inactive until released, matching Actions.Reset.
func (m *Players) SetDisconnectPolicy(policy DisconnectPolicy)SetDisconnectPolicy configures how m handles mid-game controller disconnects, reconnections, press-to-reassign recovery, and single-player keyboard/touch fallback.
Updating the policy while players are already disconnected immediately applies fallback and pause transitions to match the new policy.
func (m *Players) Step()Step polls live controllers once (when WatchGamepads is attached), reconciles any mid-game controller disconnects, reconnects, or press-to-reassign transitions, routes controllers to their assigned players, steps every player's Actions, and delivers any DisconnectPolicy callbacks. Call it once at the start of each game.Loop.Update step.
func (m *Players) Unassign(index int) boolUnassign removes all device assignments (controller, keyboard, and pointer) from player index and releases any inputs they held. Returns false if index is out of range.
func (m *Players) UnassignGamepad(index int) boolUnassignGamepad removes the controller assignment from player index and releases any inputs it held. Returns false if index is out of range or player index had no controller assigned.
func (m *Players) UnassignKeyboard(index int) boolUnassignKeyboard stops routing keyboard events from m to player index and releases any keys held on that player. Returns false if index is out of range or player index was not assigned to the keyboard.
func (m *Players) UnassignPointer(index int) boolUnassignPointer stops routing touch, mouse, and pointer-lock events from m to player index and releases any touches, held mouse buttons, or pending pointer deltas on that player. Returns false if index is out of range or player index was not assigned to pointer events.
func (m *Players) UnassignedGamepads() []gamepad.PadUnassignedGamepads returns a copy of the controllers m last read that are not currently assigned to any player, sorted by controller ID.
func (m *Players) WatchGamepads(cx *core.Scope)WatchGamepads makes m poll connected controllers from cx's app once on every Step with gamepad.Pads and route each controller to the player assigned to its ID.
Polling stops once cx is disposed, and while cx's core.Access refuses core.AccessGamepad no controller is read. Passing nil stops watching and releases every controller input across all players.
func (m *Players) WatchKeys(cx *core.Scope) (stop func())WatchKeys watches the keys held anywhere on cx's window once and routes them to every player assigned to the keyboard (AssignKeyboard), until cx is disposed, WatchKeys is called again, or stop is called, which releases watched keys on every player.
type PointerAxis uint8PointerAxis identifies one direction of the relative mouse motion a view hears while it holds the pointer lock.
const (
// PointerAxisNone is the zero PointerAxis, which always reads 0.
PointerAxisNone PointerAxis = iota
// PointerX is relative motion to the right, in the units NSGo's View.OnPointerDelta reports; motion to the left is negative.
PointerX
// PointerY is relative motion down, in the units NSGo's View.OnPointerDelta reports; motion up is negative.
PointerY
)func (p PointerAxis) String() stringString returns a stable name for p.
type PointerAxisOptions struct {
// Sensitivity multiplies the motion, such as radians of camera turn per unit of motion (1 when zero, negative or not finite).
Sensitivity float64
// Invert negates the motion, as an inverted look axis does.
Invert bool
}PointerAxisOptions configures how one bound pointer axis scales relative mouse motion.
type Prompt struct {
// Label is the human-readable prompt text, such as "Tap Jump", "Click", "[Space]", "[A]", or "[Cross]".
Label string
// Icon is an optional icon asset or sprite key, such as "key_space" or "gamepad_ps_cross".
Icon string
// Glyph is an optional compact button or key symbol, such as "Space", "A", or "Cross".
Glyph string
}Prompt describes how an action should be shown in a HUD for a specific input device.
type PromptTable struct {
// contains filtered or unexported fields
}PromptTable maps (action, DeviceKind) pairs to HUD Prompts with a device fallback chain.
The zero value is ready to use.
func DefaultPromptTable() *PromptTableDefaultPromptTable returns a PromptTable pre-populated with prompts for common game actions across touch, mouse, keyboard, and Xbox/PlayStation/Nintendo/generic gamepads.
func NewPromptTable() *PromptTableNewPromptTable returns an empty PromptTable.
func (t *PromptTable) Delete(action string, device DeviceKind)Delete removes the prompt registered for (action, device).
func (t *PromptTable) Lookup(action string, device DeviceKind) (Prompt, bool)Lookup returns the prompt explicitly registered for (action, device) without consulting the fallback chain.
func (t *PromptTable) Prompt(action string, device DeviceKind) PromptPrompt resolves the prompt for (action, device) using the device fallback chain (e.g. GamepadPlayStation -> GamepadGeneric -> Keyboard -> action name).
func (t *PromptTable) PromptFor(action string, tracker *DeviceTracker) PromptPromptFor resolves the prompt for action using tracker.LastDevice(), subscribing any active reactive computation to device changes.
func (t *PromptTable) Set(action string, device DeviceKind, prompt Prompt)Set stores prompt for (action, device).
func (t *PromptTable) SetMany(action string, prompts map[DeviceKind]Prompt)SetMany stores multiple per-device prompts for action.
type ReconnectEvent struct {
// PlayerIndex is the 0-based index of the recovered player slot.
PlayerIndex int
// Player is the recovered player slot.
Player *Player
// PreviousGamepadID is the controller ID that had disconnected.
PreviousGamepadID int
// NewGamepadID is the controller ID now assigned to the player.
NewGamepadID int
// Reassigned reports whether NewGamepadID differs from PreviousGamepadID.
Reassigned bool
// FallbackActive is false once controller control is restored.
FallbackActive bool
// ShouldPause reports whether Players still requires gameplay to remain paused after this reconnect (for example, because another player is still disconnected).
ShouldPause bool
}ReconnectEvent describes a disconnected player recovering a game controller, either by reconnecting the same controller or by reassigning to another controller.
type RumbleStep struct {
LowFreq float32
HighFreq float32
Duration time.Duration
}RumbleStep is one segment of a rumble or haptic pattern. LowFreq and HighFreq are motor strengths in [0, 1]; setting both to 0 inserts a silent pause for Duration.
type VirtualButton struct {
// Center and Radius define a circular button when Radius > 0.
Center core.Point
Radius float32
// Bounds defines a rectangular button when Radius <= 0.
Bounds core.Bounds
// Label is optional text drawn centered inside the button.
Label string
// Action is the action name driven by this button in VirtualPad and Actions.
Action string
// contains filtered or unexported fields
}VirtualButton is a circular or rectangular on-screen button with multi-touch finger tracking.
func (b *VirtualButton) Contains(p core.Point) boolContains reports whether p lies inside the button's circular or rectangular hit area.
func (b *VirtualButton) Draw(d *core.Drawing, style VirtualStyle)Draw draws the button and its optional label into d, leaving d's state unchanged.
func (b *VirtualButton) OnTouch(ev core.TouchEvent)OnTouch feeds a touch event directly to the button when used standalone without a VirtualPad.
func (b *VirtualButton) Pressed() boolPressed reports whether at least one finger is currently pressing the button.
func (b *VirtualButton) Reset()Reset releases all fingers tracked by the button.
type VirtualPad struct {
// MapPoint, when set, transforms touch positions from view coordinates before hit-testing and updating sticks and buttons. Returning false ignores the touch point.
MapPoint func(core.Point) (core.Point, bool)
Sticks []*VirtualStick
Buttons []*VirtualButton
// contains filtered or unexported fields
}VirtualPad owns a collection of VirtualSticks and VirtualButtons, routes multi-touch fingers without controls stealing each other's touches, optionally wires into Actions, and draws all controls into a core.Drawing.
func (p *VirtualPad) AddButton(b *VirtualButton) *VirtualButtonAddButton adds b to p and returns b.
func (p *VirtualPad) AddStick(s *VirtualStick) *VirtualStickAddStick adds s to p and returns s.
func (p *VirtualPad) Attach(v *core.View)Attach wires p.OnTouch onto v, chaining any existing v.OnTouch callback.
func (p *VirtualPad) Axis(name string) float64Axis returns the current axis value in [-1, 1] for name from p's sticks (or 1 if a button with Action == name is pressed).
func (p *VirtualPad) BindActions(a *Actions)BindActions connects p to a (or disconnects from any previous Actions when a is nil).
func (p *VirtualPad) Draw(d *core.Drawing, style VirtualStyle)Draw draws all sticks and buttons in p into d.
func (p *VirtualPad) OnTouch(ev core.TouchEvent)OnTouch routes ev to p's buttons and sticks so each touch finger stays owned by the control that captured it.
func (p *VirtualPad) Pressed(action string) boolPressed reports whether any button in p bound to action is currently pressed.
func (p *VirtualPad) Reset()Reset releases all active sticks, buttons, and tracked finger ownership.
type VirtualStick struct {
// Name optionally identifies the stick. When AxisXName or AxisYName is empty and Name is set, VirtualPad exposes them as Name+"_x" and Name+"_y".
Name string
// AxisXName and AxisYName name the horizontal and vertical axes exposed through VirtualPad.Axis and Actions.Axis.
AxisXName string
AxisYName string
// Zone is the touch-down activation rectangle. On a fixed stick with an empty Zone, touches inside the circle (Center, Radius) activate it.
Zone core.Bounds
// Center is the resting base center of the stick.
Center core.Point
// Radius is the maximum travel radius of the knob in points.
Radius float32
// DeadZone is the radial dead-zone fraction in [0, 1). Displacements inside DeadZone*Radius yield 0; displacements beyond it rescale smoothly to [0, 1].
DeadZone float32
// Floating, when true, re-centers the stick's base on the touch-down point inside Zone and returns it to Center on release.
Floating bool
// AxisX and AxisY hold the stick's current normalized outputs in [-1, 1].
AxisX float64
AxisY float64
// contains filtered or unexported fields
}VirtualStick is a fixed or floating on-screen thumbstick that captures a single touch finger and outputs normalized AxisX and AxisY values in [-1, 1] with radial dead-zone rescaling.
func (s *VirtualStick) Active() boolActive reports whether a touch finger is currently captured by the stick.
func (s *VirtualStick) BasePosition() core.PointBasePosition returns the current center of the stick's base ring.
func (s *VirtualStick) Draw(d *core.Drawing, style VirtualStyle)Draw draws the stick's base ring and knob into d, leaving d's state unchanged.
func (s *VirtualStick) KnobPosition() core.PointKnobPosition returns the current center of the stick's thumb knob.
func (s *VirtualStick) OnTouch(ev core.TouchEvent)OnTouch feeds a touch event directly to the stick when used standalone without a VirtualPad.
func (s *VirtualStick) Reset()Reset releases any captured finger and returns the stick to its neutral center.
type VirtualStyle struct {
BaseFill core.Color
BaseStroke core.Color
BaseStrokeWidth float32
KnobFill core.Color
KnobActiveFill core.Color
KnobRadiusRatio float32
ButtonFill core.Color
ButtonPressedFill core.Color
ButtonStroke core.Color
ButtonStrokeWidth float32
ButtonCornerRadius float32
LabelColor core.Color
LabelFont core.Font
}VirtualStyle controls how VirtualStick and VirtualButton draw themselves into a core.Drawing.
Zero fields fall back to DefaultVirtualStyle so VirtualStyle{} draws a visible default overlay.
func DefaultVirtualStyle() VirtualStyleDefaultVirtualStyle returns a translucent white-on-dark overlay style for virtual sticks and buttons.