Documentation
¶
Overview ¶
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 ¶
- Constants
- func EncodeTouchLayout(l TouchLayout) ([]byte, error)
- func RegisterTouchControlKind(kind string, factory TouchControlFactory)
- func RegisterTouchIcon(name string, icon VirtualIcon)
- func TouchControlKinds() []string
- func ValidateTouchLayout(l TouchLayout) error
- type AccessibleControl
- type ActionAssist
- type Actions
- func (a *Actions) ActionAssist(name string) ActionAssist
- func (a *Actions) ActionNames() []string
- func (a *Actions) Assists() Assists
- 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) LoadReplace(store core.Storage, key string) (bool, error)
- func (a *Actions) LockPointer(cx *core.Scope, ref *core.Ref) bool
- func (a *Actions) MashableActions() []string
- 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) ReleaseToggles()
- 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) SetActionAssist(name string, spec ActionAssist)
- func (a *Actions) SetAssists(assists Assists)
- func (a *Actions) SetAxis(name string, value float64)
- func (a *Actions) SetPaused(paused bool)
- func (a *Actions) SetStepRate(rate int)
- func (a *Actions) Step()
- func (a *Actions) StepRate() int
- func (a *Actions) ToggleActive(name string) bool
- func (a *Actions) ToggleableActions() []string
- 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 Assists
- type ButtonControl
- type DPadDirection
- type DeviceKind
- type 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 (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 (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 (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) Orientation() MotionOrientation
- func (m *MotionInput) Paused() bool
- func (m *MotionInput) Reset()
- func (m *MotionInput) ResetCalibration()
- func (m *MotionInput) SetOptions(opts MotionOptions)
- func (m *MotionInput) SetOrientation(orientation MotionOrientation)
- func (m *MotionInput) SetPaused(paused bool)
- func (m *MotionInput) SetWindowSize(size core.Size)
- func (m *MotionInput) Start(cx *core.Scope) error
- func (m *MotionInput) Step()
- func (m *MotionInput) Stop()
- type MotionOptions
- type MotionOrientation
- type Player
- func (p *Player) ActionAssist(name string) ActionAssist
- func (p *Player) Actions() *Actions
- func (p *Player) Assists() Assists
- 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) ReleaseToggles()
- func (p *Player) SetActionAssist(name string, spec ActionAssist)
- func (p *Player) SetAssists(assists Assists)
- func (p *Player) ToggleActive(name string) bool
- func (p *Player) UsesKeyboard() bool
- func (p *Player) UsesPointer() bool
- type 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) ReleaseToggles()
- func (m *Players) Reset()
- func (m *Players) SetDisconnectPolicy(policy DisconnectPolicy)
- func (m *Players) SetPaused(paused bool)
- func (m *Players) SetStepRate(rate int)
- func (m *Players) Step()
- func (m *Players) StepRate() int
- 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 (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 TouchControl
- type TouchControlFactory
- type TouchControlInfo
- type TouchControlSpec
- type TouchControls
- func (t *TouchControls) Alpha() float32
- func (t *TouchControls) Attach(v *core.View)
- func (t *TouchControls) BindActions(a *Actions)
- func (t *TouchControls) Button(id string) *VirtualButton
- func (t *TouchControls) Control(id string) TouchControl
- func (t *TouchControls) Controls() []TouchControlInfo
- func (t *TouchControls) DPad(id string) *VirtualDPad
- func (t *TouchControls) Draw(d *core.Drawing)
- func (t *TouchControls) Layout() TouchLayout
- func (t *TouchControls) Load(store core.Storage, key string) (bool, error)
- func (t *TouchControls) Pad() *VirtualPad
- func (t *TouchControls) Reset()
- func (t *TouchControls) Resize(size core.Size, safe core.Edges)
- func (t *TouchControls) Save(store core.Storage, key string) error
- func (t *TouchControls) SetLayout(l TouchLayout) error
- func (t *TouchControls) SetMirrored(mirrored bool)
- func (t *TouchControls) SetVisible(visible bool)
- func (t *TouchControls) Stick(id string) *VirtualStick
- func (t *TouchControls) Tracker() *DeviceTracker
- func (t *TouchControls) Update(dt time.Duration)
- func (t *TouchControls) Visible() bool
- func (t *TouchControls) Wake()
- type TouchLayout
- type TouchOffset
- type TouchSize
- type VirtualButton
- type VirtualButtonMode
- type VirtualControl
- type VirtualDPad
- func (p *VirtualDPad) ActionNames() []string
- func (p *VirtualDPad) ActionPressed(name string) bool
- func (p *VirtualDPad) Active() bool
- func (p *VirtualDPad) AxisValues(yield func(name string, value float64))
- func (p *VirtualDPad) Claim(id int, pt core.Point) bool
- func (p *VirtualDPad) Contains(pt core.Point) bool
- func (p *VirtualDPad) Direction() DPadDirection
- func (p *VirtualDPad) Draw(d *core.Drawing, style VirtualStyle)
- func (p *VirtualDPad) Move(id int, pt core.Point)
- func (p *VirtualDPad) OnTouch(ev core.TouchEvent)
- func (p *VirtualDPad) Release(id int)
- func (p *VirtualDPad) Reset()
- type VirtualIcon
- type VirtualPad
- func (p *VirtualPad) AddButton(b *VirtualButton) *VirtualButton
- func (p *VirtualPad) AddControl(c VirtualControl) VirtualControl
- 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
Examples ¶
Constants ¶
const ( // DefaultStepRate is the fixed update rate in steps per second assumed by // timed motor assists (MinPress, AcceptDelay, MashRate) when SetStepRate has // not been called. DefaultStepRate = 60 // DefaultMashRate is the synthetic press rate in presses per second used for // MashToHold when an action enables mash assist without declaring a custom MashRate. DefaultMashRate = 10.0 )
const ( AnchorTopLeft = "topLeft" AnchorTop = "top" AnchorTopRight = "topRight" AnchorLeft = "left" AnchorCenter = "center" AnchorRight = "right" AnchorBottomLeft = "bottomLeft" AnchorBottom = "bottom" AnchorBottomRight = "bottomRight" )
The anchors a TouchControlSpec is placed against: a corner, the middle of an edge, or the center of the safe area.
const ( // TouchKindButton is a VirtualButton: action, with text or icon, mode and shape. TouchKindButton = "button" // TouchKindDPad is a VirtualDPad: up, down, left and right actions, axisX and axisY axes, ways and deadZone. TouchKindDPad = "dpad" // TouchKindStick is a VirtualStick with an up-positive Y axis: axisX and axisY axes, deadZone, floating and radius. TouchKindStick = "stick" )
The control kinds this package registers; RegisterTouchControlKind adds others.
const ( TouchModeHold = "hold" TouchModeToggle = "toggle" TouchModeTap = "tap" TouchShapeCircle = "circle" TouchShapeRect = "rect" )
The modes and shapes a button control takes.
const DefaultDPadDeadZone = 0.2
DefaultDPadDeadZone is the dead zone a VirtualDPad uses when its DeadZone is zero or negative: the inner fifth of its radius selects no direction.
const DefaultGamepadDeadZone = 0.15
DefaultGamepadDeadZone is the stick dead zone GamepadAxisOptions uses when its DeadZone is 0: stick deflections up to this magnitude read 0.
const MinTouchTarget = 44
MinTouchTarget is the smallest width and height, in points, TouchControls gives a control however small the screen, the 44-point minimum Apple's and Google's guidelines set for a touch target.
const TouchLayoutSchemaComment = "# yaml-language-server: $schema=" + TouchLayoutSchemaURL
TouchLayoutSchemaComment is the first line EncodeTouchLayout writes: a YAML comment pointing a YAML language server at TouchLayoutSchemaURL. ParseTouchLayout ignores it like any other comment.
const TouchLayoutSchemaURL = "https://game.nsgo.dev/schemas/touchlayout.v1.json"
TouchLayoutSchemaURL is where the JSON Schema of version 1 touch layouts is published. EncodeTouchLayout writes it in a yaml-language-server comment on the first line so editors and AI tools validate and complete layout files as they are written.
const TouchLayoutVersion = 1
TouchLayoutVersion is the touch layout schema version this package reads and writes.
Variables ¶
This section is empty.
Functions ¶
func EncodeTouchLayout ¶
func EncodeTouchLayout(l TouchLayout) ([]byte, error)
EncodeTouchLayout validates l and writes it as deterministic 2-space YAML prefixed with TouchLayoutSchemaComment: fields in a fixed order, Options sorted by key, durations in Go's shortest form such as "4s", and reference, offset and size in flow style. The same layout always encodes to the same bytes, and a canonical document, one EncodeTouchLayout wrote, round-trips through ParseTouchLayout and EncodeTouchLayout byte for byte; another document is normalized to that form, losing its comments other than the schema line.
func RegisterTouchControlKind ¶
func RegisterTouchControlKind(kind string, factory TouchControlFactory)
RegisterTouchControlKind makes kind a control kind TouchLayout documents can name, built by factory. Call it from an init function, as database/sql drivers register; it panics when kind is empty, factory is nil or kind is already registered, button, dpad and stick included.
func RegisterTouchIcon ¶
func RegisterTouchIcon(name string, icon VirtualIcon)
RegisterTouchIcon makes name an icon a button's spec can name in its icon field. This package registers arrowUp, arrowDown, arrowLeft and arrowRight. It panics when name is empty, icon is nil or name is already registered.
func TouchControlKinds ¶
func TouchControlKinds() []string
TouchControlKinds returns the sorted names of every registered control kind.
func ValidateTouchLayout ¶
func ValidateTouchLayout(l TouchLayout) error
ValidateTouchLayout checks that l follows the version 1 schema: the version, a positive reference size, a valid fade, and controls with unique IDs, known anchors, positive sizes and, for the kinds this package registers, only the fields their kind takes. A kind no one registered is accepted here and refused by NewTouchControls, so a layout parses before the plugins that define its kinds load.
Errors are *loaderr.Error values naming the field.
Types ¶
type AccessibleControl ¶
type AccessibleControl interface {
// Accessibility returns the control's role, such as core.RoleSwitch for a switch, and whether it is selected, such as that switch being on.
Accessibility() (role core.Role, selected bool)
}
AccessibleControl is an optional interface a TouchControl implements to describe itself to assistive technology. TouchControls.Draw names a control that implements it with the role and selected state it returns, a ButtonControl as a button selected while pressed, and any other control as a group.
type ActionAssist ¶
type ActionAssist struct {
// Toggle reports whether the action may be latched as a toggle by player assists.
Toggle bool
// Mash reports whether the action is a rapid-press ("mash") mechanic that
// MashToHold may satisfy with a hold or a single latched press.
Mash bool
// MashRate is the synthetic press rate in presses per second used when
// MashToHold is active for this action. Zero or negative uses DefaultMashRate.
MashRate float64
}
ActionAssist declares which player motor assists an action opts into.
Menu or navigation actions leave Toggle and Mash false so global options such as a11y.Assist.HoldToToggle never latch them.
type Actions ¶
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)
// Wake, when set (for example to loop.MarkDirty on an OnDemand game.Loop), is called whenever input arrives so an idle loop wakes to run a Step and draw the result.
Wake func()
// Mixer, when set, has its Unblock called on a press, touch or key press a sees, retrying any music tracks blocked by browser autoplay policies (audio.NotAllowed) until NSGo signals audio unlock directly (nsgo-dev/nsgo#2675).
Mixer *sound.Mixer
// 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.
Example ¶
Actions turns touches into named actions and axes, sampled once per fixed step: here the left and right halves of a phone screen steer, and BindAxis reads them as one axis.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/input"
"github.com/nsgo-dev/nsgo/core"
)
func touchAt(phase core.TouchPhase, id int, x, y core.Points) core.TouchEvent {
return core.TouchEvent{Phase: phase, Touches: []core.Touch{{ID: id, Position: core.Point{X: x, Y: y}, Changed: true}}}
}
func main() {
a := input.NewActions()
a.Bind("left", input.TouchRegion(core.Bounds{Size: core.Size{Width: 200, Height: 400}}))
a.Bind("right", input.TouchRegion(core.Bounds{Origin: core.Point{X: 200}, Size: core.Size{Width: 200, Height: 400}}))
a.BindAxis("steer", "left", "right")
a.OnTouch(touchAt(core.TouchStart, 1, 300, 200))
a.Step()
fmt.Println(a.Pressed("right"), a.JustPressed("right"), a.Axis("steer"))
a.Step()
fmt.Println(a.Pressed("right"), a.JustPressed("right"))
a.OnTouch(touchAt(core.TouchEnd, 1, 300, 200))
a.Step()
fmt.Println(a.Pressed("right"), a.JustReleased("right"), a.Axis("steer"))
}
Output: true true 1 true false false true 0
func (*Actions) ActionAssist ¶
func (a *Actions) ActionAssist(name string) ActionAssist
ActionAssist returns the declared ActionAssist specification for name, or the zero value if none has been declared.
func (*Actions) ActionNames ¶
ActionNames returns the sorted names of all actions bound, referenced by axes or virtual pads, or currently active or injected on a.
func (*Actions) Attach ¶
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 (*Actions) AttachMotion ¶
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 (*Actions) Axis ¶
Axis 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 (*Actions) AxisBinding ¶
AxisBinding returns the negative and positive action names bound to axis name.
func (*Actions) Bind ¶
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 (*Actions) BindAxis ¶
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 (*Actions) BindGamepadAxis ¶
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 (*Actions) BindMotionAxis ¶
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 (*Actions) BindPointerAxis ¶
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 (*Actions) BindVirtualPad ¶
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 (*Actions) Bindings ¶
Bindings returns a copy of the inputs currently bound to name, or nil if name is unbound.
func (*Actions) CalibrateMotion ¶
func (a *Actions) CalibrateMotion()
CalibrateMotion captures the current tilt reading as the neutral hold angle on a's MotionInput.
func (*Actions) ClearAxis ¶
ClearAxis removes an injected analog contribution previously set with SetAxis for axis name.
func (*Actions) Delta ¶
Delta 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 (*Actions) GamepadAxisBinding ¶
GamepadAxisBinding returns the stick axis and options bound to name with BindGamepadAxis.
func (*Actions) Gamepads ¶
Gamepads returns a copy of the controller state a last read, sorted by controller ID.
func (*Actions) JustPressed ¶
JustPressed reports whether name became pressed on the current step (either rising from released on the previous step, or latched by a fresh press since the previous step such as consecutive taps across an idle gap).
func (*Actions) JustReleased ¶
JustReleased reports whether name was pressed on the previous step and is no longer pressed on the current step.
func (*Actions) Load ¶
Load merges action and axis bindings saved in store under key into a, and reports whether key was present.
Each action, axis, motion axis, pointer axis or gamepad axis present in the saved value replaces a's binding for that name; an entry saved as explicitly unbound (an empty or "none"-only action list, an empty axis, or axis "none") unbinds that name. Names absent from the saved value keep their current bindings, so defaults added in a newer build stay bound when loading an older save. Use LoadReplace to replace all of a's bindings with the saved snapshot.
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 (*Actions) LoadReplace ¶
LoadReplace replaces all of a's action and axis bindings with those saved in store under key, dropping any binding absent from the saved value, and reports whether key was present.
When key is absent or the stored value fails to decode, LoadReplace behaves like Load: it leaves a's bindings untouched and returns false with nil or a *loaderr.Error.
func (*Actions) LockPointer ¶
LockPointer 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 (*Actions) MashableActions ¶
MashableActions returns the sorted names of actions declared with Mash: true.
func (*Actions) Motion ¶
func (a *Actions) Motion() *MotionInput
Motion returns the MotionInput currently attached to a, or nil if none is attached.
func (*Actions) MotionAxisBinding ¶
func (a *Actions) MotionAxisBinding(name string) (MotionAxis, MotionAxisOptions, bool)
MotionAxisBinding returns the motion axis and options bound to name.
func (*Actions) OnContextMenu ¶
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 (*Actions) OnGamepads ¶
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 (*Actions) OnKeyDown ¶
OnKeyDown 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 (*Actions) OnKeyUp ¶
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 (*Actions) OnMotion ¶
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 (*Actions) OnMouseLeave ¶
func (a *Actions) OnMouseLeave(ev core.MouseEvent)
OnMouseLeave clears held mouse buttons when the pointer leaves the view.
func (*Actions) OnMouseMove ¶
func (a *Actions) OnMouseMove(ev core.MouseEvent)
OnMouseMove records mouse movement and any held button from a view's OnMouseMove callback.
func (*Actions) OnPointerDelta ¶
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 (*Actions) OnPressDown ¶
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 (*Actions) OnPressUp ¶
func (a *Actions) OnPressUp(ev core.PressEvent)
OnPressUp records a primary pointer release from a view's OnPressUp callback.
func (*Actions) OnTouch ¶
func (a *Actions) OnTouch(ev core.TouchEvent)
OnTouch records a touch event from a view's OnTouch callback.
func (*Actions) PointerAxisBinding ¶
func (a *Actions) PointerAxisBinding(name string) (PointerAxis, PointerAxisOptions, bool)
PointerAxisBinding returns the pointer axis and options bound to name.
func (*Actions) PointerDelta ¶
PointerDelta returns the relative mouse motion, right and down, heard between the previous Step and the current one, unscaled.
func (*Actions) PointerLockRequested ¶
PointerLockRequested 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 (*Actions) Press ¶
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 (*Actions) ReleaseToggles ¶
func (a *Actions) ReleaseToggles()
ReleaseToggles releases all latched Toggle states and active MashToHold holds without discarding bindings, assist configuration, or accept-delay cooldowns. On the next Step, previously latched actions report JustReleased.
func (*Actions) Reset ¶
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 (*Actions) ResetMotionCalibration ¶
func (a *Actions) ResetMotionCalibration()
ResetMotionCalibration clears any neutral tilt offset on a's MotionInput.
func (*Actions) Save ¶
Save writes all of a's action, axis, motion axis, pointer axis and game controller stick axis bindings as JSON into store under key, including explicit unbindings made with Unbind, UnbindAxis, UnbindMotionAxis, UnbindPointerAxis or UnbindGamepadAxis so a later Load keeps them unbound rather than restoring defaults. It fails with *core.StorageFullError when the storage is full.
func (*Actions) SelectAnyGamepad ¶
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 (*Actions) SelectGamepad ¶
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 (*Actions) SelectedGamepad ¶
SelectedGamepad returns the controller ID chosen with SelectGamepad, and false when a reads every controller.
func (*Actions) SetActionAssist ¶
func (a *Actions) SetActionAssist(name string, spec ActionAssist)
SetActionAssist declares which motor assists action name opts into.
Once any action on a declares an ActionAssist (including via project.File.BindInput), Toggle and MashToHold only affect actions that explicitly enable Toggle or Mash, ensuring undeclared menu or pause actions are never latched.
func (*Actions) SetAssists ¶
SetAssists sets the player-chosen motor assists applied during Step. Negative durations are clamped to 0, and action lists are trimmed, deduplicated, and sorted. Removing an action from Toggle or MashToHold releases its latched toggle or mash state immediately.
func (*Actions) SetAxis ¶
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 (*Actions) SetPaused ¶
SetPaused notifies a that the game loop paused or resumed. When paused is true, all latched toggles and in-flight mash or slow-key holds are released so no toggled action stays active across a pause menu. Suitable for loop.OnPause.
func (*Actions) SetStepRate ¶
SetStepRate sets the fixed step rate in steps per second used to convert timed motor assists (MinPress, AcceptDelay, MashRate) into fixed steps. Non-positive values restore DefaultStepRate (60).
func (*Actions) Step ¶
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 (*Actions) StepRate ¶
StepRate returns the fixed step rate in steps per second used for timed motor assists (DefaultStepRate when unset).
func (*Actions) ToggleActive ¶
ToggleActive reports whether action name is currently latched on by a Toggle assist.
func (*Actions) ToggleableActions ¶
ToggleableActions returns the sorted names of actions declared with Toggle: true.
func (*Actions) Trigger ¶
Trigger latches action name so it registers as pressed on the next Step call, even if name has no physical Input bindings.
func (*Actions) Unbind ¶
Unbind removes all inputs bound to name. Save records the unbinding so a later Load keeps name unbound rather than restoring a default.
func (*Actions) UnbindAxis ¶
UnbindAxis removes the axis binding for name. Save records the unbinding so a later Load keeps name unbound rather than restoring a default.
func (*Actions) UnbindGamepadAxis ¶
UnbindGamepadAxis removes the gamepad axis binding for name. Save records the unbinding so a later Load keeps name unbound rather than restoring a default.
func (*Actions) UnbindMotionAxis ¶
UnbindMotionAxis removes the motion axis binding for name. Save records the unbinding so a later Load keeps name unbound rather than restoring a default.
func (*Actions) UnbindPointerAxis ¶
UnbindPointerAxis removes the pointer axis binding for name. Save records the unbinding so a later Load keeps name unbound rather than restoring a default.
func (*Actions) UnbindVirtualPad ¶
func (a *Actions) UnbindVirtualPad(pad *VirtualPad)
UnbindVirtualPad disconnects pad from a.
func (*Actions) UnlockPointer ¶
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 (*Actions) WatchGamepads ¶
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. When Wake is set and at least one controller is connected in the foreground, a also watches connected controllers on display frames and calls Wake when a button press/release or bound stick axis changes so an idle OnDemand loop wakes to step. 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 (*Actions) WatchKeys ¶
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 (*Actions) WatchMotion ¶
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 Assists ¶
type Assists struct {
// Toggle lists action names that latch pressed on the first accepted press
// and release on the next accepted press.
Toggle []string
// MashToHold lists action names whose rapid-press mechanics count a single
// hold (or latched press when also in Toggle) as repeated presses at the
// action's declared MashRate (DefaultMashRate when unset).
MashToHold []string
// MinPress is the minimum continuous duration a binding must be held before
// a press is accepted (slow keys). Zero or negative disables the filter.
MinPress time.Duration
// AcceptDelay is the cooldown period after an accepted press of an action
// during which further presses of that action are ignored (bounce keys).
// Zero or negative disables the cooldown.
AcceptDelay time.Duration
}
Assists holds player-chosen motor accessibility assists evaluated during each fixed Actions.Step so live play and replays produce identical snapshots.
type ButtonControl ¶
type ButtonControl interface {
VirtualControl
// Button returns the VirtualButton the control presses, the same one on every call.
Button() *VirtualButton
}
ButtonControl is a VirtualControl that is a VirtualButton underneath, such as a plugin's custom-drawn or cooldown button that wraps one. A VirtualPad treats it as one of its buttons: a finger touching down on it is claimed before sticks and other controls, follows it and, with SlideBetweenButtons, slides onto and off it; its ButtonTap press ends after one Actions.Step; and TouchControls names it as a button for assistive technology. The pad drives the VirtualButton itself, so the control's Claim, Move and Release are not called for its fingers.
type DPadDirection ¶
type DPadDirection uint8
DPadDirection is a set of d-pad directions, one bit each; a diagonal on an 8-way VirtualDPad holds two.
const ( DPadUp DPadDirection = 1 << iota DPadDown DPadLeft DPadRight )
The four directions of a VirtualDPad.
func (DPadDirection) Has ¶
func (d DPadDirection) Has(dir DPadDirection) bool
Has reports whether d includes every direction in dir.
type DeviceKind ¶
type DeviceKind uint8
DeviceKind identifies the input device class the player last used.
const ( DeviceUnknown DeviceKind = iota DeviceTouch DeviceMouse DeviceKeyboard DeviceGamepadXbox DeviceGamepadPlayStation DeviceGamepadNintendo DeviceGamepadGeneric )
func DetectGamepadKind ¶
func DetectGamepadKind(name string) DeviceKind
DetectGamepadKind infers the gamepad brand from a controller name string, falling back to DeviceGamepadGeneric.
Example ¶
DetectGamepadKind recognizes a controller family from the name the platform reports.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/input"
)
func main() {
for _, name := range []string{"Xbox Wireless Controller", "Pro Controller", "USB Gamepad"} {
fmt.Println(input.DetectGamepadKind(name))
}
}
Output: xbox nintendo gamepad
func (DeviceKind) IsGamepad ¶
func (d DeviceKind) IsGamepad() bool
IsGamepad reports whether d is one of the gamepad device kinds.
func (DeviceKind) String ¶
func (d DeviceKind) String() string
String returns a short canonical name for d.
type DeviceTracker ¶
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 ¶
func NewDeviceTracker(cx *core.Scope, initial DeviceKind) *DeviceTracker
NewDeviceTracker returns a DeviceTracker initialized to initial. When cx is non-nil, it creates a reactive core.Signal[DeviceKind] owned by cx.
func (*DeviceTracker) Attach ¶
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 (*DeviceTracker) LastDevice ¶
func (t *DeviceTracker) LastDevice() DeviceKind
LastDevice 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 (*DeviceTracker) LastDeviceUntracked ¶
func (t *DeviceTracker) LastDeviceUntracked() DeviceKind
LastDeviceUntracked returns the most recently used input device without subscribing to t's signal.
func (*DeviceTracker) OnChange ¶
func (t *DeviceTracker) OnChange(fn func(DeviceKind))
OnChange registers fn to run whenever the tracked device changes.
func (*DeviceTracker) OnContextMenu ¶
func (t *DeviceTracker) OnContextMenu(core.ContextMenuEvent)
OnContextMenu records a secondary mouse click and switches to DeviceMouse.
func (*DeviceTracker) OnGamepad ¶
func (t *DeviceTracker) OnGamepad(kind DeviceKind)
OnGamepad records gamepad activity for kind. Non-gamepad kinds default to DeviceGamepadGeneric.
func (*DeviceTracker) OnGamepadActivity ¶
func (t *DeviceTracker) OnGamepadActivity(controllerName string)
OnGamepadActivity records gamepad activity using a controller name string to infer its brand.
func (*DeviceTracker) OnKey ¶
func (t *DeviceTracker) OnKey(core.KeyEvent)
OnKey records hardware keyboard activity and switches to DeviceKeyboard.
func (*DeviceTracker) OnMouseMove ¶
func (t *DeviceTracker) OnMouseMove(core.MouseEvent)
OnMouseMove records mouse pointer movement and switches the active device to DeviceMouse.
func (*DeviceTracker) OnPressDown ¶
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 (*DeviceTracker) OnTouch ¶
func (t *DeviceTracker) OnTouch(ev core.TouchEvent)
OnTouch records touch activity and switches the active device to DeviceTouch.
func (*DeviceTracker) OnWheel ¶
func (t *DeviceTracker) OnWheel(core.WheelEvent)
OnWheel records mouse wheel activity and switches to DeviceMouse.
func (*DeviceTracker) Reset ¶
func (t *DeviceTracker) Reset()
Reset clears active touch tracking while keeping the last-used device.
func (*DeviceTracker) SetDevice ¶
func (t *DeviceTracker) SetDevice(d DeviceKind)
SetDevice explicitly sets the last-used device and notifies subscribers if it changed.
func (*DeviceTracker) Signal ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
func DefaultGestureConfig() GestureConfig
DefaultGestureConfig returns balanced mobile/tablet thresholds for GestureRecognizer.
type GestureEvent ¶
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 ¶
type GestureKind uint8
GestureKind identifies a touch gesture recognized by GestureRecognizer.
const ( GestureNone GestureKind = iota GestureTap GestureDoubleTap GestureLongPress GestureSwipeLeft GestureSwipeRight GestureSwipeUp GestureSwipeDown GesturePinchIn GesturePinchOut )
func (GestureKind) String ¶
func (g GestureKind) String() string
String returns a human-readable name for g.
type GestureRecognizer ¶
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)
// Wake, when set (for example to loop.MarkDirty on an OnDemand game.Loop), is called when touch input arrives on g so an idle loop wakes to run Update. When Wake is nil and g is bound to an Actions with Wake set, g wakes through Actions.
Wake func()
// 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.
Example ¶
A GestureRecognizer reads taps, swipes and pinches from touches as the game steps, and can trigger actions bound to them.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/input"
"github.com/nsgo-dev/nsgo/core"
)
func touchAt(phase core.TouchPhase, id int, x, y core.Points) core.TouchEvent {
return core.TouchEvent{Phase: phase, Touches: []core.Touch{{ID: id, Position: core.Point{X: x, Y: y}, Changed: true}}}
}
func main() {
a := input.NewActions()
g := input.NewGestureRecognizer(a)
g.BindGesture("dash", input.GestureSwipeRight)
g.OnTouch(touchAt(core.TouchStart, 1, 50, 100))
g.Update(time.Second / 60)
g.OnTouch(touchAt(core.TouchMove, 1, 200, 100))
g.OnTouch(touchAt(core.TouchEnd, 1, 200, 100))
g.Update(time.Second / 60)
a.Step()
for _, e := range g.Events() {
fmt.Println(e.Kind)
}
fmt.Println("dash:", a.JustPressed("dash"))
}
Output: swipe_right dash: true
func NewGestureRecognizer ¶
func NewGestureRecognizer(a *Actions) *GestureRecognizer
NewGestureRecognizer returns a GestureRecognizer optionally wired to trigger actions on a.
func (*GestureRecognizer) Attach ¶
func (g *GestureRecognizer) Attach(v *core.View)
Attach wires g.OnTouch onto v, chaining any existing v.OnTouch callback.
func (*GestureRecognizer) BindActions ¶
func (g *GestureRecognizer) BindActions(a *Actions)
BindActions wires g to trigger bound actions on a (or disconnects when a is nil).
func (*GestureRecognizer) BindGesture ¶
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 (*GestureRecognizer) Events ¶
func (g *GestureRecognizer) Events() []GestureEvent
Events returns a copy of all gestures recognized on the most recent Update step.
func (*GestureRecognizer) OnTouch ¶
func (g *GestureRecognizer) OnTouch(ev core.TouchEvent)
OnTouch records touch activity for gesture recognition.
func (*GestureRecognizer) PinchScale ¶
func (g *GestureRecognizer) PinchScale() float64
PinchScale returns the current two-finger pinch scale ratio (currentDistance / initialDistance), or 1 when no pinch is active.
func (*GestureRecognizer) Reset ¶
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 (*GestureRecognizer) Triggered ¶
func (g *GestureRecognizer) Triggered(kind GestureKind) bool
Triggered reports whether kind fired on the most recent Update step.
func (*GestureRecognizer) UnbindGesture ¶
func (g *GestureRecognizer) UnbindGesture(action string)
UnbindGesture removes all gesture bindings for action.
func (*GestureRecognizer) Update ¶
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 ¶
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 ¶
NewHaptics 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 (*Haptics) Error ¶
func (h *Haptics) Error()
Error plays an error/failure outcome haptic (core.HapticError).
func (*Haptics) Heavy ¶
func (h *Haptics) Heavy()
Heavy plays a heavy impact haptic (core.HapticHeavy).
func (*Haptics) Light ¶
func (h *Haptics) Light()
Light plays a light impact haptic (core.HapticLight).
func (*Haptics) Load ¶
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 (*Haptics) Medium ¶
func (h *Haptics) Medium()
Medium plays a medium impact haptic (core.HapticMedium).
func (*Haptics) Play ¶
Play emits kind through core.Scope.PlayHaptic when h is enabled and in foreground. Invalid haptic values are ignored.
func (*Haptics) PlayPattern ¶
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 (*Haptics) Rigid ¶
func (h *Haptics) Rigid()
Rigid plays a rigid impact haptic (core.HapticRigid).
func (*Haptics) Rumble ¶
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 (*Haptics) Save ¶
Save writes h.Enabled into store under key. It fails with *core.StorageFullError when storage is full.
func (*Haptics) Selection ¶
func (h *Haptics) Selection()
Selection plays a subtle selection-change tick (core.HapticSelection).
func (*Haptics) SetEnabled ¶
SetEnabled sets h.Enabled and immediately stops any active rumble when disabling.
func (*Haptics) StopRumble ¶
func (h *Haptics) StopRumble()
StopRumble immediately stops any active rumble or pattern and zeroes the gamepad motor sink.
func (*Haptics) Success ¶
func (h *Haptics) Success()
Success plays a positive outcome haptic (core.HapticSuccess).
type Input ¶
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 ¶
GamepadButton 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 ¶
Key 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 ¶
KeyCode 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 ¶
func MouseButton(button core.MouseButton) Input
MouseButton returns an input that is active while button is held down on the view. core.MouseButtonNone is never active.
func MouseRegion ¶
func MouseRegion(rect core.Bounds, button core.MouseButton) Input
MouseRegion 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 ¶
TouchRegion 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 ¶
type InputKind uint8
InputKind 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 ¶
type MotionAxis uint8
MotionAxis 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 screen X axis (right, in g units), // rotated from the natural device frame according to MotionOptions.Orientation. TiltX // TiltY is device tilt along the screen Y axis (up, in g units), // rotated from the natural device frame according to MotionOptions.Orientation. TiltY // TiltZ is device tilt along the screen Z axis (out of the screen, in g units). TiltZ // GyroX is angular velocity around the screen X axis (rad/s), // rotated from the natural device frame according to MotionOptions.Orientation. GyroX // GyroY is angular velocity around the screen Y axis (rad/s), // rotated from the natural device frame according to MotionOptions.Orientation. GyroY // GyroZ is angular velocity around the screen Z axis (rad/s). GyroZ )
type MotionAxisOptions ¶
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 ¶
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.
Example ¶
A MotionInput turns device tilt and rotation into axes in [-1, 1], sampled once per game step. Calibrate takes the way the player holds the device as neutral. In a game, Start (or WatchMotion) feeds it the device's sensors; here OnMotion feeds it samples directly, as a test or a replay does.
package main
import (
"fmt"
"math"
"github.com/nsgo-dev/game/pkg/input"
"github.com/nsgo-dev/nsgo/core"
)
func main() {
const g = 9.80665 // m/s² in one g
m := input.NewMotionInput(input.MotionOptions{})
hold := core.SensorVector{X: 0, Y: 0.5 * g, Z: 0.85 * g}
// The first tilt sample after Calibrate becomes the neutral hold.
m.Calibrate()
m.OnMotion(core.MotionSample{Sensor: core.SensorDeviceMotion, Gravity: hold})
m.Step()
fmt.Printf("calibrated: %v tiltX %.2f\n", m.Calibrated(), m.Axis(input.TiltX))
// Tilting right by half a g and turning at a quarter turn per second.
hold.X = 0.5 * g
m.OnMotion(core.MotionSample{Sensor: core.SensorDeviceMotion, Gravity: hold, RotationRate: core.SensorVector{Z: math.Pi / 2}})
m.Step()
fmt.Printf("tiltX %.2f gyroZ %.2f\n", m.Axis(input.TiltX), m.Axis(input.GyroZ))
}
Output: calibrated: true tiltX 0.00 tiltX 0.50 gyroZ 0.50
func NewMotionInput ¶
func NewMotionInput(opts MotionOptions) *MotionInput
NewMotionInput returns a MotionInput configured with opts. Call Start(cx) to subscribe to live device sensors, or feed samples directly with OnMotion.
func WatchMotion ¶
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), pauses while the app is in background, and can be paused with SetPaused (e.g. from game.Loop.OnPause).
func (*MotionInput) Active ¶
func (m *MotionInput) Active() bool
Active reports whether m currently has a live, unstopped sensor stream.
func (*MotionInput) Axis ¶
func (m *MotionInput) Axis(axis MotionAxis) float64
Axis returns the stepped value of axis in [-1, 1] using m's default options.
func (*MotionInput) AxisWith ¶
func (m *MotionInput) AxisWith(axis MotionAxis, opts MotionAxisOptions) float64
AxisWith returns the stepped value of axis in [-1, 1] using per-axis opts, with zero fields falling back to m's defaults.
func (*MotionInput) Calibrate ¶
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 (*MotionInput) Calibrated ¶
func (m *MotionInput) Calibrated() bool
Calibrated reports whether a neutral tilt offset has been captured.
func (*MotionInput) Calibration ¶
func (m *MotionInput) Calibration() core.SensorVector
Calibration returns the captured neutral tilt vector in g units.
func (*MotionInput) OnMotion ¶
func (m *MotionInput) OnMotion(sample core.MotionSample)
OnMotion ingests one core.MotionSample (from WatchMotion, a unit test, or a replay). Samples are rotated from the natural device frame into screen axes according to Orientation before smoothing and calibration. Updated values are held until the next Step call so reads stay stable within a fixed game.Loop step. Calls while paused are ignored.
func (*MotionInput) Options ¶
func (m *MotionInput) Options() MotionOptions
Options returns m's current MotionOptions.
func (*MotionInput) Orientation ¶
func (m *MotionInput) Orientation() MotionOrientation
Orientation returns the resolved orientation currently applied to incoming motion vectors (one of MotionOrientationPortrait, MotionOrientationPortraitUpsideDown, MotionOrientationLandscapeLeft or MotionOrientationLandscapeRight).
func (*MotionInput) Paused ¶
func (m *MotionInput) Paused() bool
Paused reports whether m is currently paused via SetPaused.
func (*MotionInput) Reset ¶
func (m *MotionInput) Reset()
Reset clears live and snapped sensor readings without changing options, calibration or the active stream.
func (*MotionInput) ResetCalibration ¶
func (m *MotionInput) ResetCalibration()
ResetCalibration clears any neutral tilt offset captured by Calibrate.
func (*MotionInput) SetOptions ¶
func (m *MotionInput) SetOptions(opts MotionOptions)
SetOptions updates Orientation, LandscapeSide, DeadZone, Sensitivity, TiltRange, GyroRange, Smoothing and OnError at runtime. Changing Sensors or Interval takes effect on the next Start or resume from SetPaused(false).
func (*MotionInput) SetOrientation ¶
func (m *MotionInput) SetOrientation(orientation MotionOrientation)
SetOrientation sets m's orientation mode at runtime without replacing other MotionOptions.
func (*MotionInput) SetPaused ¶
func (m *MotionInput) SetPaused(paused bool)
SetPaused stops the active motion sensor stream while paused and restarts it on resume, preserving calibration and options. While paused, live and snapped readings are cleared and incoming samples are ignored so no stale tilt or gyro values persist across a pause menu.
Pair with game.Loop.OnPause (loop.OnPause = motion.SetPaused) so sensors stop while the game is paused as well as when the app enters the background.
func (*MotionInput) SetWindowSize ¶
func (m *MotionInput) SetWindowSize(size core.Size)
SetWindowSize supplies the active view or window size used to infer portrait vs. landscape when MotionOptions.Orientation is MotionOrientationAuto. When Start or WatchMotion is active, cx.Env().Window() updates this automatically.
func (*MotionInput) Start ¶
func (m *MotionInput) Start(cx *core.Scope) error
Start subscribes to live device motion sensors on cx using m's options. Any previously active stream on m is stopped first. If m is currently paused via SetPaused(true), Start records cx and waits to open the sensor stream until SetPaused(false) is called.
func (*MotionInput) Step ¶
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 (*MotionInput) Stop ¶
func (m *MotionInput) Stop()
Stop cancels the active sensor stream, if any, and stops watching the scope.
type MotionOptions ¶
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
// Orientation rotates tilt and gyro vectors from the natural device frame into screen axes
// before smoothing and calibration. Zero defaults to MotionOrientationPortrait.
Orientation MotionOrientation
// LandscapeSide chooses which landscape side MotionOrientationAuto selects when the window is
// wider than tall. Setting MotionOrientationLandscapeRight selects landscape right; any other
// value (including zero) selects MotionOrientationLandscapeLeft.
LandscapeSide MotionOrientation
// 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 MotionOrientation ¶
type MotionOrientation uint8
MotionOrientation selects how device motion vectors are rotated from NSGo's right-handed natural device frame (+X right, +Y up, +Z out of the screen) into screen axes before smoothing and calibration.
const ( // MotionOrientationPortrait uses the natural device frame (device top at screen top). // The zero value keeps portrait so callers that omit Orientation behave unchanged. MotionOrientationPortrait MotionOrientation = iota // MotionOrientationPortraitUpsideDown rotates 180° (device top at screen bottom): // screen (+X, +Y, +Z) = device (-X, -Y, +Z). MotionOrientationPortraitUpsideDown // MotionOrientationLandscapeLeft rotates 90° counter-clockwise (device top at screen left, // matching NSGo's core.OrientationLandscapeLeft on Android, HarmonyOS and Web): // screen (+X, +Y, +Z) = device (-Y, +X, +Z). MotionOrientationLandscapeLeft // MotionOrientationLandscapeRight rotates 90° clockwise (device top at screen right, // matching NSGo's core.OrientationLandscapeRight on Android, HarmonyOS and Web): // screen (+X, +Y, +Z) = device (+Y, -X, +Z). MotionOrientationLandscapeRight // MotionOrientationAuto infers portrait or landscape from the window's aspect ratio // (via cx.Env().Window() when started on a core.Scope, or SetWindowSize otherwise). // When the window is wider than tall, it uses MotionOptions.LandscapeSide // (defaulting to MotionOrientationLandscapeLeft); otherwise it uses MotionOrientationPortrait. MotionOrientationAuto )
func (MotionOrientation) String ¶
func (o MotionOrientation) String() string
String returns a stable name for o.
type Player ¶
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 (*Player) ActionAssist ¶
func (p *Player) ActionAssist(name string) ActionAssist
ActionAssist returns the declared ActionAssist specification for name on p.
func (*Player) Actions ¶
Actions returns p's Actions, where bindings, axes, virtual pads, and saved controls live. Returns nil if p is nil.
func (*Player) Delta ¶
Delta returns the relative motion of pointer axis name for p on the current step.
func (*Player) FallbackActive ¶
FallbackActive 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 (*Player) Gamepad ¶
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 (*Player) GamepadConnected ¶
GamepadConnected reports whether p has an assigned controller that is present in the latest controller snapshot.
func (*Player) GamepadDisconnected ¶
GamepadDisconnected 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 (*Player) GamepadID ¶
GamepadID returns the controller ID assigned to p and true, or (0, false) when p has no assigned controller.
func (*Player) HasDevice ¶
HasDevice reports whether at least one physical device (a controller, keyboard, or pointer) is assigned to p.
func (*Player) Index ¶
Index returns p's 0-based slot index in its Players group, or -1 if p is nil.
func (*Player) JustPressed ¶
JustPressed reports whether action name became pressed for p on the current step.
func (*Player) JustReleased ¶
JustReleased reports whether action name was released for p on the current step.
func (*Player) ReleaseToggles ¶
func (p *Player) ReleaseToggles()
ReleaseToggles releases all latched toggles and active mash holds on p.
func (*Player) SetActionAssist ¶
func (p *Player) SetActionAssist(name string, spec ActionAssist)
SetActionAssist declares which motor assists action name opts into for p.
func (*Player) SetAssists ¶
SetAssists sets the player-chosen motor assists applied to p's Actions during Step.
func (*Player) ToggleActive ¶
ToggleActive reports whether action name is currently latched on by a Toggle assist for p.
func (*Player) UsesKeyboard ¶
UsesKeyboard reports whether keyboard events from p's Players group are routed to p.
func (*Player) UsesPointer ¶
UsesPointer reports whether touch, mouse, and pointer-lock events from p's Players group are routed to p.
type Players ¶
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.
Example ¶
Players routes separate game controllers (and optional shared keyboard key sets) to independent per-player Actions sampled once per step.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/input"
"github.com/nsgo-dev/nsgo/gamepad"
)
func main() {
players := input.NewPlayers(2)
for _, p := range players.All() {
p.Actions().Bind("jump", input.GamepadButton(gamepad.ButtonSouth))
p.Actions().BindGamepadAxis("move", gamepad.AxisLeftX, input.GamepadAxisOptions{DeadZone: -1})
}
players.AssignGamepad(0, 1)
players.AssignGamepad(1, 2)
pad1 := gamepad.Pad{ID: 1, Axes: [gamepad.AxisCount]float32{-0.5, 0, 0, 0}}
pad1.Buttons[gamepad.ButtonSouth] = 1
pad2 := gamepad.Pad{ID: 2, Axes: [gamepad.AxisCount]float32{0.75, 0, 0, 0}}
players.OnGamepads([]gamepad.Pad{pad1, pad2})
players.Step()
fmt.Printf("p0: jump=%v move=%.2f\n", players.Player(0).JustPressed("jump"), players.Player(0).Axis("move"))
fmt.Printf("p1: jump=%v move=%.2f\n", players.Player(1).JustPressed("jump"), players.Player(1).Axis("move"))
}
Output: p0: jump=true move=-0.50 p1: jump=false move=0.75
func NewPlayers ¶
NewPlayers 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 (*Players) Add ¶
Add appends a new player slot with an empty Actions and no assigned devices, and returns it.
func (*Players) All ¶
All returns a copy of the player slots in index order, or nil when m has no players.
func (*Players) AssignGamepad ¶
AssignGamepad 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 (*Players) AssignKeyboard ¶
AssignKeyboard 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 (*Players) AssignPointer ¶
AssignPointer 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 (*Players) AssignUnassignedGamepads ¶
AssignUnassignedGamepads 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 (*Players) Attach ¶
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 (*Players) DisconnectPolicy ¶
func (m *Players) DisconnectPolicy() DisconnectPolicy
DisconnectPolicy returns the disconnect and reconnect policy currently configured on m.
func (*Players) DisconnectedPlayers ¶
DisconnectedPlayers returns the player slots currently awaiting controller reconnect, in ascending slot index order, or nil if no player is disconnected.
func (*Players) Gamepads ¶
Gamepads returns a copy of the controller state m last read, sorted by controller ID.
func (*Players) NextUnassigned ¶
NextUnassigned returns the first player slot with no device assigned, or nil when every slot has a device.
func (*Players) OnContextMenu ¶
func (m *Players) OnContextMenu(ev core.ContextMenuEvent)
OnContextMenu forwards ev to every player assigned to pointer events.
func (*Players) OnGamepads ¶
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 (*Players) OnKeyDown ¶
OnKeyDown forwards ev to every player assigned to the keyboard and reports whether any of them consumed it.
func (*Players) OnMouseLeave ¶
func (m *Players) OnMouseLeave(ev core.MouseEvent)
OnMouseLeave forwards ev to every player assigned to pointer events.
func (*Players) OnMouseMove ¶
func (m *Players) OnMouseMove(ev core.MouseEvent)
OnMouseMove forwards ev to every player assigned to pointer events.
func (*Players) OnPointerDelta ¶
OnPointerDelta forwards relative pointer motion to every player assigned to pointer events.
func (*Players) OnPressDown ¶
func (m *Players) OnPressDown(ev core.PressEvent)
OnPressDown forwards ev to every player assigned to pointer events.
func (*Players) OnPressUp ¶
func (m *Players) OnPressUp(ev core.PressEvent)
OnPressUp forwards ev to every player assigned to pointer events.
func (*Players) OnTouch ¶
func (m *Players) OnTouch(ev core.TouchEvent)
OnTouch forwards ev to every player assigned to pointer events.
func (*Players) PausedByDisconnect ¶
PausedByDisconnect reports whether m has paused gameplay via DisconnectPolicy.PauseOnDisconnect because at least one disconnected player is awaiting a controller without fallback.
func (*Players) PlayerByGamepad ¶
PlayerByGamepad returns the player currently assigned to controller padID, or nil if no player owns padID.
func (*Players) PollGamepads ¶
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 (*Players) ReleaseToggles ¶
func (m *Players) ReleaseToggles()
ReleaseToggles releases all latched toggles and active mash holds on every player's Actions.
func (*Players) Reset ¶
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 (*Players) SetDisconnectPolicy ¶
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 (*Players) SetPaused ¶
SetPaused forwards pause state to every player's Actions, releasing latched toggles when paused. Suitable for loop.OnPause.
func (*Players) SetStepRate ¶
SetStepRate sets the fixed step rate in steps per second on every player's Actions (and any players added later) for timed motor assists.
func (*Players) Step ¶
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 (*Players) StepRate ¶
StepRate returns the fixed step rate in steps per second configured on m (DefaultStepRate when unset).
func (*Players) Unassign ¶
Unassign 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 (*Players) UnassignGamepad ¶
UnassignGamepad 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 (*Players) UnassignKeyboard ¶
UnassignKeyboard 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 (*Players) UnassignPointer ¶
UnassignPointer 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 (*Players) UnassignedGamepads ¶
UnassignedGamepads returns a copy of the controllers m last read that are not currently assigned to any player, sorted by controller ID.
func (*Players) WatchGamepads ¶
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.
type PointerAxis ¶
type PointerAxis uint8
PointerAxis 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 (PointerAxis) String ¶
func (p PointerAxis) String() string
String returns a stable name for p.
type PointerAxisOptions ¶
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 ¶
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 ¶
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.
Example ¶
A PromptTable picks the button label to show for an action on the device the player last used, which a DeviceTracker follows.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/input"
"github.com/nsgo-dev/nsgo/core"
)
func main() {
prompts := input.NewPromptTable()
prompts.SetMany("jump", map[input.DeviceKind]input.Prompt{
input.DeviceKeyboard: {Label: "[Space]", Glyph: "Space"},
input.DeviceGamepadXbox: {Label: "[A]", Glyph: "A"},
input.DeviceGamepadPlayStation: {Label: "[Cross]", Glyph: "Cross"},
input.DeviceTouch: {Label: "Tap Jump"},
})
var tracker input.DeviceTracker
tracker.OnKey(core.KeyEvent{})
fmt.Println(prompts.PromptFor("jump", &tracker).Label)
tracker.OnGamepadActivity("DualSense Wireless Controller")
fmt.Println(tracker.LastDevice(), prompts.PromptFor("jump", &tracker).Label)
}
Output: [Space] playstation [Cross]
func DefaultPromptTable ¶
func DefaultPromptTable() *PromptTable
DefaultPromptTable returns a PromptTable pre-populated with prompts for common game actions across touch, mouse, keyboard, and Xbox/PlayStation/Nintendo/generic gamepads.
func NewPromptTable ¶
func NewPromptTable() *PromptTable
NewPromptTable returns an empty PromptTable.
func (*PromptTable) Delete ¶
func (t *PromptTable) Delete(action string, device DeviceKind)
Delete removes the prompt registered for (action, device).
func (*PromptTable) Lookup ¶
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 (*PromptTable) Prompt ¶
func (t *PromptTable) Prompt(action string, device DeviceKind) Prompt
Prompt resolves the prompt for (action, device) using the device fallback chain (e.g. GamepadPlayStation -> GamepadGeneric -> Keyboard -> action name).
func (*PromptTable) PromptFor ¶
func (t *PromptTable) PromptFor(action string, tracker *DeviceTracker) Prompt
PromptFor resolves the prompt for action using tracker.LastDevice(), subscribing any active reactive computation to device changes.
func (*PromptTable) Set ¶
func (t *PromptTable) Set(action string, device DeviceKind, prompt Prompt)
Set stores prompt for (action, device).
func (*PromptTable) SetMany ¶
func (t *PromptTable) SetMany(action string, prompts map[DeviceKind]Prompt)
SetMany stores multiple per-device prompts for action.
type ReconnectEvent ¶
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 ¶
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 TouchControl ¶
type TouchControl interface {
VirtualControl
// Place moves and sizes the control to frame, in the view's points, as TouchControls computes it from the spec's anchor, offset and size; scale is the view points per reference point applied, for other lengths the spec gives such as a stick's radius. TouchControls calls it on every Resize, SetLayout and SetMirrored.
Place(frame core.Bounds, scale float32)
}
TouchControl is one control a TouchControls layer builds from a TouchControlSpec: a VirtualControl that the layer also places on screen. The kinds this package registers build a VirtualButton, VirtualDPad or VirtualStick; a plugin implements TouchControl for a kind of its own and registers it with RegisterTouchControlKind.
type TouchControlFactory ¶
type TouchControlFactory func(spec TouchControlSpec) (TouchControl, error)
TouchControlFactory builds a control from its spec. It returns an error for a spec it cannot build, such as an option it does not know, which NewTouchControls reports against the control.
type TouchControlInfo ¶
type TouchControlInfo struct {
// ID, Kind and Label are the control's spec fields.
ID, Kind, Label string
// Frame is where the control is on screen, in the view's points.
Frame core.Bounds
}
TouchControlInfo describes one placed control of a TouchControls layer.
type TouchControlSpec ¶
type TouchControlSpec struct {
// ID names the control uniquely within the layout, for TouchControls.Control and for a player's saved edits.
ID string `yaml:"id" schema:"required,minLength=1"`
// Kind is the control's kind: button, dpad, stick, or a name registered with RegisterTouchControlKind.
Kind string `yaml:"kind" schema:"required,minLength=1"`
// Anchor is the point of the safe area the control is placed against.
Anchor string `yaml:"anchor" schema:"required,enum=topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight"`
// Offset moves the control from its anchor toward the inside of the screen.
Offset TouchOffset `yaml:"offset,omitempty,flow"`
// Size is the control's width and height; a round control fits a circle inside it.
Size TouchSize `yaml:"size,flow" schema:"required"`
// Label is the control's accessibility label, read by screen readers and shown by TouchControls.Controls.
Label string `yaml:"label,omitempty"`
// Action is the action a button presses.
Action string `yaml:"action,omitempty"`
// Text is the caption drawn on a button.
Text string `yaml:"text,omitempty"`
// Icon names a glyph registered with RegisterTouchIcon that a button draws in place of Text.
Icon string `yaml:"icon,omitempty"`
// Mode is a button's behavior: hold (the default), toggle or tap.
Mode string `yaml:"mode,omitempty" schema:"enum=hold|toggle|tap"`
// Shape is a button's shape: circle (the default) or rect.
Shape string `yaml:"shape,omitempty" schema:"enum=circle|rect"`
// Ways is 4 (the default) or 8 for a d-pad that also selects diagonals.
Ways int `yaml:"ways,omitempty" schema:"enum=4|8"`
// Up, Down, Left and Right are the actions a d-pad's directions press.
Up string `yaml:"up,omitempty"`
Down string `yaml:"down,omitempty"`
Left string `yaml:"left,omitempty"`
Right string `yaml:"right,omitempty"`
// AxisX and AxisY are the axes a d-pad or stick drives, AxisY positive up.
AxisX string `yaml:"axisX,omitempty"`
AxisY string `yaml:"axisY,omitempty"`
// DeadZone is the fraction of a d-pad's or stick's radius in [0, 1) that reads as rest; 0 keeps the control's default.
DeadZone float64 `yaml:"deadZone,omitempty" schema:"minimum=0,exclusiveMaximum=1"`
// Floating makes a stick re-center on the finger that touches down anywhere in its frame.
Floating bool `yaml:"floating,omitempty"`
// Radius is a stick's knob travel in reference points; 0 uses half the smaller side of Size.
Radius float64 `yaml:"radius,omitempty" schema:"minimum=0"`
// Options holds settings for a kind a plugin registers, as strings: a value the YAML would read as a number, boolean or null is written quoted, such as speed: "3", so it reads back the same. The kinds this package registers refuse it.
Options map[string]string `yaml:"options,omitempty"`
}
TouchControlSpec declares one control of a TouchLayout. The fields a kind does not take are refused for the kinds this package registers; a kind a plugin registers reads the fields it documents, and Options for anything else.
type TouchControls ¶
type TouchControls struct {
// Style is how the controls draw; its zero value draws DefaultVirtualStyle.
Style VirtualStyle
// Haptics, when set, plays a selection tick each time a finger presses a control.
Haptics *Haptics
// OnWake, when set (for example to loop.MarkDirty on an OnDemand game.Loop), is called when touch controls receive input or change visibility or layout so an idle loop wakes to step and redraw. When OnWake is nil and t is bound to an Actions with Wake set, t wakes through Actions.
OnWake func()
// contains filtered or unexported fields
}
TouchControls is a layer of on-screen controls built from a TouchLayout: it places them in the safe area at a size that follows the screen, drives the same named actions and axes as the keyboard and game controllers through Actions, shows itself when the player touches the screen and hides when they type or use a controller, fades when idle, mirrors for left-handed play, and saves a player's edited layout.
Call BindActions with the game's Actions, which routes the view's touches to the controls, Attach on the game's view after Actions.Attach, Resize whenever the view's size or safe area changes, Update once per game.Loop step after Actions.Step, and Draw from the game's Canvas. Controls work in the view's points, so they ignore Actions.MapPoint.
Its methods are called on the engine's goroutine, as core.View's callbacks and game.Loop.Update are.
func NewTouchControls ¶
func NewTouchControls(cx *core.Scope, layout TouchLayout) (*TouchControls, error)
NewTouchControls builds the controls layout declares. It returns an error, a *loaderr.Error naming the control's field, when layout is invalid, names a kind no one registered, or a kind's factory refuses a control.
The controls start visible when cx's primary pointer is coarse (Env.Pointer is core.PointerCoarse, as on phones and tablets) and hidden otherwise, until the player touches the screen; a nil cx starts them hidden. They are placed on a screen of layout's reference size until the first Resize.
func (*TouchControls) Alpha ¶
func (t *TouchControls) Alpha() float32
Alpha returns the opacity t draws its controls with: 0 while hidden, and between IdleAlpha and 1 as they fade.
func (*TouchControls) Attach ¶
func (t *TouchControls) Attach(v *core.View)
Attach wires t's device tracking and touch responder onto v, chaining v's existing callbacks, so a touch anywhere on v shows the controls, a touch on one of t's controls claims the responder without LetNative (blocking native page/scroll-view drags while the finger is down), and a key v hears hides them. Call it after Actions.Attach. It hears touches and keys alone: a press synthesized from a touch can report Keyboard when a key was the last input, which must not hide the controls the finger is using.
func (*TouchControls) BindActions ¶
func (t *TouchControls) BindActions(a *Actions)
BindActions connects t's controls to a, so their actions and axes read through a's Pressed and Axis beside the keyboard's and controllers', a routes the touches it hears to them, and t watches a for keyboard and controller use. A nil a disconnects t.
func (*TouchControls) Button ¶
func (t *TouchControls) Button(id string) *VirtualButton
Button returns the VirtualButton of the control id when it is a ButtonControl, a button kind or a plugin's, or nil.
func (*TouchControls) Control ¶
func (t *TouchControls) Control(id string) TouchControl
Control returns the control whose spec has id, or nil.
func (*TouchControls) Controls ¶
func (t *TouchControls) Controls() []TouchControlInfo
Controls describes every control in layout order, with where it is on screen.
func (*TouchControls) DPad ¶
func (t *TouchControls) DPad(id string) *VirtualDPad
DPad returns the VirtualDPad of the d-pad control id, or nil when id is not a d-pad.
func (*TouchControls) Draw ¶
func (t *TouchControls) Draw(d *core.Drawing)
Draw draws the visible controls into d at their current opacity, leaving d's state unchanged, and names each one as a canvas node for assistive technology and tests, with its label and the test ID "touch-" followed by its id: a ButtonControl as a button selected while pressed, an AccessibleControl with the role it reports, and any other control as a group. The nodes are named whatever the opacity, so controls an idleAlpha of 0 fades out of sight still reach screen readers and tests while they take touches. d is the drawing of a Canvas that covers the view t is placed on.
func (*TouchControls) Layout ¶
func (t *TouchControls) Layout() TouchLayout
Layout returns a copy of the layout t shows, mirrored or not as SetMirrored last set it.
func (*TouchControls) Load ¶
Load replaces t's layout with the one saved in store under key, and reports whether key was present. When key is absent, Load keeps t's layout and returns false, nil. When the saved layout does not parse or build, Load keeps t's layout and returns false and a *loaderr.Error that names key as its file.
func (*TouchControls) Pad ¶
func (t *TouchControls) Pad() *VirtualPad
Pad returns the VirtualPad t routes touches through, for a game that reads its controls directly.
func (*TouchControls) Reset ¶
func (t *TouchControls) Reset()
Reset releases every finger on the controls and turns toggled buttons off. Call it with Actions.Reset, which also resets the controls while they are bound.
func (*TouchControls) Resize ¶
func (t *TouchControls) Resize(size core.Size, safe core.Edges)
Resize places the controls on a view of size whose edges system UI covers by safe, such as Env.SafeArea or core.Insets of the view's scope. Calling it again with the same values does nothing.
func (*TouchControls) Save ¶
func (t *TouchControls) Save(store core.Storage, key string) error
Save writes t's layout into store under key as the YAML EncodeTouchLayout writes, so a player's edited layout survives a restart. It fails with *core.StorageFullError when storage is full.
func (*TouchControls) SetLayout ¶
func (t *TouchControls) SetLayout(l TouchLayout) error
SetLayout replaces t's controls with those l declares, such as a layout the player edited, and places them on the current screen. Fingers on the old controls are released. On error t keeps its controls.
func (*TouchControls) SetMirrored ¶
func (t *TouchControls) SetMirrored(mirrored bool)
SetMirrored swaps the controls between the left and right of the screen when mirrored is true, for left-handed play, and back when it is false.
func (*TouchControls) SetVisible ¶
func (t *TouchControls) SetVisible(visible bool)
SetVisible shows or hides the controls. Showing makes them fully opaque; hiding lifts every finger on them, keeping toggled buttons on. Touches still reach hidden controls, and a press on one shows them again. Either way the next switch of device counts: a key or a controller hides controls shown this way, and a touch shows controls hidden this way.
func (*TouchControls) Stick ¶
func (t *TouchControls) Stick(id string) *VirtualStick
Stick returns the VirtualStick of the stick control id, or nil when id is not a stick.
func (*TouchControls) Tracker ¶
func (t *TouchControls) Tracker() *DeviceTracker
Tracker returns the DeviceTracker that shows t on touch and hides it on keyboard and controller use. Feed it more events, such as a game's own key handler, to switch t the same way.
func (*TouchControls) Update ¶
func (t *TouchControls) Update(dt time.Duration)
Update advances the idle fade by dt and hides the controls when a key or a game controller the bound Actions reads starts being used. Call it once per game.Loop step, after Actions.Step.
func (*TouchControls) Visible ¶
func (t *TouchControls) Visible() bool
Visible reports whether t draws its controls.
func (*TouchControls) Wake ¶
func (t *TouchControls) Wake()
Wake makes the controls fully opaque and restarts the idle fade, as a press does. Call it when the controls come back into view after the game stopped drawing them, such as when play starts or resumes from a pause, so they do not first appear already faded by the time spent elsewhere.
type TouchLayout ¶
type TouchLayout struct {
// Version is the schema version; it must equal TouchLayoutVersion (1).
Version int `yaml:"version" schema:"required"`
// Reference is the screen size, in points, the layout's offsets and sizes are written for, such as a landscape phone's 844 by 390.
Reference TouchSize `yaml:"reference,flow" schema:"required"`
// MaxScale caps how much the layout grows on a screen larger than Reference, such as a tablet's; 0 leaves it uncapped.
MaxScale float64 `yaml:"maxScale,omitempty" schema:"minimum=0"`
// IdleAfter is how long the controls stay fully opaque after the last touch on them before fading to IdleAlpha, as a Go duration such as "3s"; 0 never fades them.
IdleAfter time.Duration `yaml:"idleAfter,omitempty"`
// IdleAlpha is the opacity in [0, 1] the controls fade to once idle.
IdleAlpha float64 `yaml:"idleAlpha,omitempty" schema:"minimum=0,maximum=1"`
// Mirrored swaps every control between the left and right of the screen, for left-handed play.
Mirrored bool `yaml:"mirrored,omitempty"`
// Controls lists the controls, drawn in order; a later control draws over an earlier one.
Controls []TouchControlSpec `yaml:"controls,omitempty"`
}
TouchLayout is the root of a versioned YAML document that declares a game's on-screen touch controls, which NewTouchControls builds.
Lengths are in points on a screen of Reference size. TouchControls scales them by the smaller of the safe area's width and height over Reference's, so the layout keeps its proportions on any screen, and never makes a control smaller than MinTouchTarget.
func ParseTouchLayout ¶
func ParseTouchLayout(data []byte) (TouchLayout, error)
ParseTouchLayout decodes a YAML touch layout and validates it with ValidateTouchLayout. Unknown fields, a second YAML document and any version other than TouchLayoutVersion are refused.
Errors are *loaderr.Error values carrying the line, column, field path and a fix; a caller that read the layout from a file names it with loaderr.WithFile.
type TouchOffset ¶
TouchOffset moves a control from its anchor, in reference points, toward the inside of the screen: X from a left or right anchor's edge and Y from a top or bottom anchor's edge, and right and down from a centered anchor.
type TouchSize ¶
type TouchSize struct {
Width float64 `yaml:"width" schema:"required,exclusiveMinimum=0"`
Height float64 `yaml:"height" schema:"required,exclusiveMinimum=0"`
}
TouchSize is a width and a height in reference points.
type VirtualButton ¶
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
// Icon, when set, is drawn centered inside the button in place of Label.
Icon VirtualIcon
// Action is the action name driven by this button in VirtualPad and Actions.
Action string
// Mode selects hold (the default), toggle or tap behavior.
Mode VirtualButtonMode
// contains filtered or unexported fields
}
VirtualButton is a circular or rectangular on-screen button with multi-touch finger tracking.
func (*VirtualButton) Contains ¶
func (b *VirtualButton) Contains(p core.Point) bool
Contains reports whether p lies inside the button's circular or rectangular hit area.
func (*VirtualButton) Draw ¶
func (b *VirtualButton) Draw(d *core.Drawing, style VirtualStyle)
Draw draws the button and its optional icon or label into d, leaving d's state unchanged.
func (*VirtualButton) Held ¶
func (b *VirtualButton) Held() bool
Held reports whether at least one finger is on the button, whatever its Mode.
func (*VirtualButton) OnTouch ¶
func (b *VirtualButton) OnTouch(ev core.TouchEvent)
OnTouch feeds a touch event directly to the button when used standalone without a VirtualPad.
func (*VirtualButton) Pressed ¶
func (b *VirtualButton) Pressed() bool
Pressed reports whether the button is pressed: while a finger is on it in ButtonHold mode, while toggled on in ButtonToggle mode, and from a touch-down until the next Actions.Step in ButtonTap mode.
func (*VirtualButton) Reset ¶
func (b *VirtualButton) Reset()
Reset releases all fingers tracked by the button, turns a toggled button off and drops a pending tap.
type VirtualButtonMode ¶
type VirtualButtonMode uint8
VirtualButtonMode selects how a VirtualButton turns the fingers on it into its pressed state.
const ( // ButtonHold presses the button while at least one finger is on it. It is the zero value. ButtonHold VirtualButtonMode = iota // ButtonToggle flips the button between pressed and released on each touch-down, and keeps that state after the finger lifts until the next touch-down or Reset. ButtonToggle // ButtonTap presses the button once per touch-down, however long the finger stays: through Actions its action is pressed for exactly one Step. A finger sliding onto it from another button in a VirtualPad with SlideBetweenButtons counts as a touch-down. ButtonTap )
type VirtualControl ¶
type VirtualControl interface {
// Claim reports whether finger id, touching down at p, starts the control; a control that returns true owns the finger until Release.
Claim(id int, p core.Point) bool
// Move reports that owned finger id moved to p.
Move(id int, p core.Point)
// Release reports that owned finger id lifted or was cancelled.
Release(id int)
// Reset releases every finger and returns the control to rest.
Reset()
// ActionNames returns the names of the actions the control drives.
ActionNames() []string
// ActionPressed reports whether the control currently presses action name.
ActionPressed(name string) bool
// AxisValues calls yield with the name and current value in [-1, 1] of every axis the control drives, zero values included.
AxisValues(yield func(name string, value float64))
// Draw draws the control into d, leaving d's state unchanged.
Draw(d *core.Drawing, style VirtualStyle)
}
VirtualControl is an on-screen control a VirtualPad routes touches to beside its sticks and buttons, such as a VirtualDPad or a control kind a plugin registers with RegisterTouchControlKind.
The pad hands each new finger to the first control whose Claim takes it and keeps sending that finger to the same control, wherever it moves, until it lifts.
type VirtualDPad ¶
type VirtualDPad struct {
// Center and Radius define the pad's circular hit area. A finger that touched down inside it keeps steering the pad when it slides past the edge.
Center core.Point
Radius float32
// Ways is 4 for up, down, left and right only, or 8 to add the diagonals; any other value means 4.
Ways int
// DeadZone is the fraction of Radius in [0, 1) around Center that selects no direction; zero or negative uses DefaultDPadDeadZone.
DeadZone float32
// Up, Down, Left and Right name the actions each direction presses; an empty name presses nothing.
Up, Down, Left, Right string
// AxisXName and AxisYName, when set, name the axes the pad drives: -1 left and +1 right on AxisXName, +1 up and -1 down on AxisYName.
AxisXName string
AxisYName string
// contains filtered or unexported fields
}
VirtualDPad is a round on-screen directional pad that one finger owns as a whole: the finger can rock or slide between directions without lifting, and the pad quantizes its offset from Center into 4 or 8 directions.
Each direction drives the action named in Up, Down, Left or Right, and AxisXName and AxisYName, when set, name axes the pad drives with -1, 0 or 1. AxisY is positive up, as a game controller's d-pad and inverted stick read. Add it to a VirtualPad with AddControl, or feed it touches with OnTouch.
func (*VirtualDPad) ActionNames ¶
func (p *VirtualDPad) ActionNames() []string
ActionNames returns the pad's non-empty direction actions.
func (*VirtualDPad) ActionPressed ¶
func (p *VirtualDPad) ActionPressed(name string) bool
ActionPressed reports whether a selected direction drives action name.
func (*VirtualDPad) Active ¶
func (p *VirtualDPad) Active() bool
Active reports whether a finger currently owns the pad.
func (*VirtualDPad) AxisValues ¶
func (p *VirtualDPad) AxisValues(yield func(name string, value float64))
AxisValues yields AxisXName and AxisYName, when set, with the selected direction's -1, 0 or 1.
func (*VirtualDPad) Claim ¶
func (p *VirtualDPad) Claim(id int, pt core.Point) bool
Claim takes finger id when it touches down inside the pad while no other finger owns it.
func (*VirtualDPad) Contains ¶
func (p *VirtualDPad) Contains(pt core.Point) bool
Contains reports whether pt lies inside the pad's circle.
func (*VirtualDPad) Direction ¶
func (p *VirtualDPad) Direction() DPadDirection
Direction returns the directions the owning finger currently selects, or 0 at rest or inside the dead zone.
func (*VirtualDPad) Draw ¶
func (p *VirtualDPad) Draw(d *core.Drawing, style VirtualStyle)
Draw draws the pad's base, its four arrows and a highlight behind each selected direction into d, leaving d's state unchanged.
func (*VirtualDPad) Move ¶
func (p *VirtualDPad) Move(id int, pt core.Point)
Move steers the pad with its owning finger.
func (*VirtualDPad) OnTouch ¶
func (p *VirtualDPad) OnTouch(ev core.TouchEvent)
OnTouch feeds a touch event directly to the pad when used standalone without a VirtualPad.
func (*VirtualDPad) Release ¶
func (p *VirtualDPad) Release(id int)
Release lets go of the owning finger.
func (*VirtualDPad) Reset ¶
func (p *VirtualDPad) Reset()
Reset releases the owning finger and clears the direction.
type VirtualIcon ¶
VirtualIcon draws a glyph into frame, the area inside a control it decorates, in color. It runs inside the control's Draw, so the drawing state it changes is restored afterwards.
func TouchIcon ¶
func TouchIcon(name string) (VirtualIcon, bool)
TouchIcon returns the icon registered as name.
type VirtualPad ¶
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
// Controls holds the pad's other controls, such as VirtualDPads.
Controls []VirtualControl
// SlideBetweenButtons, when true, hands a finger that slides off one button onto another to that button, so a thumb can rock between neighbouring buttons without lifting. A ButtonToggle button is never entered this way. Fingers owned by sticks and other controls never move to a button.
SlideBetweenButtons bool
// OnPress, when set, is called each time a finger presses something: touching down on a button, sliding onto another button, or a control whose Claim or Move newly presses one of its actions. It suits a haptic tick.
OnPress func()
// contains filtered or unexported fields
}
VirtualPad owns a collection of VirtualSticks, VirtualButtons and other VirtualControls, routes multi-touch fingers without controls stealing each other's touches, optionally wires into Actions, and draws all controls into a core.Drawing.
Example ¶
A VirtualPad draws on-screen controls and turns touches on them into axes and button presses.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/input"
"github.com/nsgo-dev/nsgo/core"
)
func touchAt(phase core.TouchPhase, id int, x, y core.Points) core.TouchEvent {
return core.TouchEvent{Phase: phase, Touches: []core.Touch{{ID: id, Position: core.Point{X: x, Y: y}, Changed: true}}}
}
func main() {
pad := input.NewVirtualPad()
pad.AddStick(&input.VirtualStick{Center: core.Point{X: 100, Y: 300}, Radius: 50, Name: "move"})
pad.AddButton(&input.VirtualButton{Center: core.Point{X: 700, Y: 300}, Radius: 40, Action: "jump"})
pad.OnTouch(touchAt(core.TouchStart, 1, 100, 300))
pad.OnTouch(touchAt(core.TouchMove, 1, 125, 300))
pad.OnTouch(touchAt(core.TouchStart, 2, 700, 300))
fmt.Println(pad.Axis("move_x"), pad.Pressed("jump"))
}
Output: 0.5 true
func (*VirtualPad) AddButton ¶
func (p *VirtualPad) AddButton(b *VirtualButton) *VirtualButton
AddButton adds b to p and returns b.
func (*VirtualPad) AddControl ¶
func (p *VirtualPad) AddControl(c VirtualControl) VirtualControl
AddControl adds c to p and returns c.
func (*VirtualPad) AddStick ¶
func (p *VirtualPad) AddStick(s *VirtualStick) *VirtualStick
AddStick adds s to p and returns s.
func (*VirtualPad) Attach ¶
func (p *VirtualPad) Attach(v *core.View)
Attach wires p.OnTouch onto v, chaining any existing v.OnTouch callback.
func (*VirtualPad) Axis ¶
func (p *VirtualPad) Axis(name string) float64
Axis returns the current axis value in [-1, 1] for name from p's sticks and controls (or 1 if a button with Action == name is pressed).
func (*VirtualPad) BindActions ¶
func (p *VirtualPad) BindActions(a *Actions)
BindActions connects p to a (or disconnects from any previous Actions when a is nil).
func (*VirtualPad) Draw ¶
func (p *VirtualPad) Draw(d *core.Drawing, style VirtualStyle)
Draw draws all sticks, controls and buttons in p into d.
func (*VirtualPad) OnTouch ¶
func (p *VirtualPad) OnTouch(ev core.TouchEvent)
OnTouch routes ev to p's buttons, controls and sticks so each touch finger stays owned by the control that captured it.
func (*VirtualPad) Pressed ¶
func (p *VirtualPad) Pressed(action string) bool
Pressed reports whether any button or control in p bound to action is currently pressing it.
func (*VirtualPad) Reset ¶
func (p *VirtualPad) Reset()
Reset releases all active sticks, buttons and controls, turns toggled buttons off and clears tracked finger ownership.
type VirtualStick ¶
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
// UpPositive, when true, makes AxisY positive while the knob is pushed up, as a game controller's stick reads with GamepadAxisOptions.Invert. By default AxisY follows screen coordinates and is positive while the knob is pushed down.
UpPositive bool
// AxisX and AxisY hold the stick's current normalized outputs in [-1, 1]. AxisX is positive to the right; AxisY is positive downward, or upward with UpPositive.
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 (*VirtualStick) Active ¶
func (s *VirtualStick) Active() bool
Active reports whether a touch finger is currently captured by the stick.
func (*VirtualStick) BasePosition ¶
func (s *VirtualStick) BasePosition() core.Point
BasePosition returns the current center of the stick's base ring.
func (*VirtualStick) Draw ¶
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 (*VirtualStick) KnobPosition ¶
func (s *VirtualStick) KnobPosition() core.Point
KnobPosition returns the current center of the stick's thumb knob.
func (*VirtualStick) OnTouch ¶
func (s *VirtualStick) OnTouch(ev core.TouchEvent)
OnTouch feeds a touch event directly to the stick when used standalone without a VirtualPad.
func (*VirtualStick) Reset ¶
func (s *VirtualStick) Reset()
Reset releases any captured finger and returns the stick to its neutral center.
type VirtualStyle ¶
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 ¶
func DefaultVirtualStyle() VirtualStyle
DefaultVirtualStyle returns a translucent white-on-dark overlay style for virtual sticks and buttons.