input

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 13 Imported by: 13 modules, 12 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Examples

Constants

View Source
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.

Variables

This section is empty.

Functions

This section is empty.

Types

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)
	// 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 NewActions

func NewActions() *Actions

NewActions returns an Actions with no bindings.

func (*Actions) ActionNames

func (a *Actions) ActionNames() []string

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

func (a *Actions) Attach(v *core.View)

Attach wires a's touch, press, mouse, context-menu, pointer-lock motion and key handlers onto v, chaining any callbacks already set on v. v hears keys only while it has the keyboard focus; WatchKeys hears them anywhere on the window. A key held as v leaves the tree stays held until Reset, as OnKeyUp says.

func (*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

func (a *Actions) Axis(name string) float64

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

func (a *Actions) AxisBinding(name string) (negative, positive string, ok bool)

AxisBinding returns the negative and positive action names bound to axis name.

func (*Actions) AxisNames

func (a *Actions) AxisNames() []string

AxisNames returns the sorted names of all axes bound or injected on a.

func (*Actions) Bind

func (a *Actions) Bind(name string, inputs ...Input)

Bind binds name to inputs, replacing any previous inputs for name. Calling Bind with no inputs unbinds name. A key name is lowercased, as Key does, so Bindings returns it lowercased.

func (*Actions) BindAxis

func (a *Actions) BindAxis(name, negative, positive string)

BindAxis binds axis name to two opposite actions: negative drives it toward -1 and positive toward +1. Calling BindAxis with two empty names unbinds the axis.

func (*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

func (a *Actions) Bindings(name string) []Input

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

func (a *Actions) ClearAxis(name string)

ClearAxis removes an injected analog contribution previously set with SetAxis for axis name.

func (*Actions) Delta

func (a *Actions) Delta(name string) float64

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

func (a *Actions) GamepadAxisBinding(name string) (gamepad.Axis, GamepadAxisOptions, bool)

GamepadAxisBinding returns the stick axis and options bound to name with BindGamepadAxis.

func (*Actions) Gamepads

func (a *Actions) Gamepads() []gamepad.Pad

Gamepads returns a copy of the controller state a last read, sorted by controller ID.

func (*Actions) JustPressed

func (a *Actions) JustPressed(name string) bool

JustPressed reports whether name became pressed on the current step and was not pressed on the previous step.

func (*Actions) JustReleased

func (a *Actions) JustReleased(name string) bool

JustReleased reports whether name was pressed on the previous step and is no longer pressed on the current step.

func (*Actions) Load

func (a *Actions) Load(store core.Storage, key string) (bool, error)

Load replaces a's action and axis bindings with those saved in store under key, and reports whether key was present.

When key is absent, Load leaves a's existing bindings as they are and returns false, nil. When the stored value is invalid JSON, has a field Load does not know or uses an unknown format, Load leaves a's bindings untouched and returns false and an error: a *loaderr.Error that names key as its file, with the line and field of the problem and how to fix it.

func (*Actions) LockPointer

func (a *Actions) LockPointer(cx *core.Scope, ref *core.Ref) bool

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) 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

func (a *Actions) OnGamepads(pads []gamepad.Pad)

OnGamepads replaces the controller state a reads with pads, such as recorded or synthetic controllers in a unit test or an input replay, and latches any button that became pressed so it registers on the next Step even if it is released before then.

While WatchGamepads has a scope attached, the next Step replaces pads with the live controllers.

func (*Actions) OnKeyDown

func (a *Actions) OnKeyDown(ev core.KeyEvent) bool

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

func (a *Actions) OnKeyUp(ev core.KeyEvent)

OnKeyUp records a key coming up from a view's OnKeyUp callback. NSGo sends it for a key that went down while the view had the keyboard focus, wherever the focus has gone since, and for every key still held as the window loses the keyboard focus, so no key stays held. It does not send it once the view has left the tree, so a key held as the attached view is removed stays held until Reset; call Reset when the game view is replaced, or use WatchKeys, which has no such view.

func (*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

func (a *Actions) OnPointerDelta(dx, dy float64)

OnPointerDelta records relative motion, right and down, from a view's OnPointerDelta callback, which NSGo calls only while that view holds the pointer lock. Motion adds up until the next Step; a value that is not finite is ignored.

func (*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

func (a *Actions) PointerDelta() (dx, dy float64)

PointerDelta returns the relative mouse motion, right and down, heard between the previous Step and the current one, unscaled.

func (*Actions) PointerLockRequested

func (a *Actions) PointerLockRequested() bool

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

func (a *Actions) Press(name string)

Press holds action name pressed across subsequent Step calls until Release or Reset is called, even if name has no physical Input bindings. Like physical input, a Press followed by Release between two Step calls is latched so it still registers for one step.

func (*Actions) Pressed

func (a *Actions) Pressed(name string) bool

Pressed reports whether name is held during the current step.

func (*Actions) Release

func (a *Actions) Release(name string)

Release ends an injected hold started by Press for action name.

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

func (a *Actions) Save(store core.Storage, key string) error

Save writes all of a's action, axis, motion axis, pointer axis and game controller stick axis bindings as JSON into store under key. It fails with *core.StorageFullError when the storage is full.

func (*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

func (a *Actions) SelectGamepad(id int)

SelectGamepad makes a read only the controller with ID id, such as one player's controller in a local multiplayer game with one Actions per player. By default a reads every connected controller.

func (*Actions) SelectedGamepad

func (a *Actions) SelectedGamepad() (id int, ok bool)

SelectedGamepad returns the controller ID chosen with SelectGamepad, and false when a reads every controller.

func (*Actions) SetAxis

func (a *Actions) SetAxis(name string, value float64)

SetAxis sets an injected analog contribution in [-1, 1] for axis name, sampled on each subsequent Step until ClearAxis or Reset is called. Non-finite (NaN) values are ignored; values outside [-1, 1] are clamped.

func (*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) Trigger

func (a *Actions) Trigger(name string)

Trigger latches action name so it registers as pressed on the next Step call, even if name has no physical Input bindings.

func (*Actions) Unbind

func (a *Actions) Unbind(name string)

Unbind removes all inputs bound to name.

func (*Actions) UnbindAxis

func (a *Actions) UnbindAxis(name string)

UnbindAxis removes the axis binding for name.

func (*Actions) UnbindGamepadAxis

func (a *Actions) UnbindGamepadAxis(name string)

UnbindGamepadAxis removes the gamepad axis binding for name.

func (*Actions) UnbindMotionAxis

func (a *Actions) UnbindMotionAxis(name string)

UnbindMotionAxis removes the motion axis binding for name.

func (*Actions) UnbindPointerAxis

func (a *Actions) UnbindPointerAxis(name string)

UnbindPointerAxis removes the pointer axis binding for name.

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

func (a *Actions) WatchGamepads(cx *core.Scope)

WatchGamepads makes a read the game controllers connected to cx's app on every Step with gamepad.Pads, so GamepadButton inputs and BindGamepadAxis axes follow the physical controllers on every target that supports them.

Step reads the controllers' state as of the current display frame, so call Step from game.Loop.Update as usual. A press and release that both happen between two Step calls are not seen. Reading stops once cx is disposed, and while cx's core.Access refuses core.AccessGamepad no controller is read. Passing nil stops reading and releases every controller input.

func (*Actions) WatchKeys

func (a *Actions) WatchKeys(cx *core.Scope) (stop func())

WatchKeys has a hear the keys held anywhere on cx's window, whichever view has the keyboard focus, until cx is disposed or stop is called, which releases the keys it heard. A key held as Reset is called counts as released until it comes up and goes down again, as it does for a focused view. It follows core.KeysDown and core.KeyCodesDown, so keys typed into a text input or composed by an input method are never held, and every held key comes up as the window loses the keyboard focus. Call it once, from the scope that runs the game.Loop.

func (*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 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)
	// 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

func NewHaptics(cx *core.Scope) *Haptics

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

func (h *Haptics) Load(store core.Storage, key string) (bool, error)

Load restores h.Enabled from store under key and reports whether key was present. When key is absent or invalid, h.Enabled is left untouched. An invalid value's error is a *loaderr.Error that names key as its file.

func (*Haptics) Medium

func (h *Haptics) Medium()

Medium plays a medium impact haptic (core.HapticMedium).

func (*Haptics) Play

func (h *Haptics) Play(kind core.Haptic)

Play emits kind through core.Scope.PlayHaptic when h is enabled and in foreground. Invalid haptic values are ignored.

func (*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

func (h *Haptics) Rumble(lowFreq, highFreq float32, duration time.Duration)

Rumble starts a timed rumble with lowFreq and highFreq motor strengths in [0, 1] for duration. Calling Rumble with duration <= 0 or both strengths <= 0 stops any active rumble. Step the rumble scheduler by calling Update(dt) from game.Loop.Update.

func (*Haptics) Rumbling

func (h *Haptics) Rumbling() bool

Rumbling reports whether a rumble or pattern is currently playing.

func (*Haptics) Save

func (h *Haptics) Save(store core.Storage, key string) error

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

func (h *Haptics) SetEnabled(enabled bool)

SetEnabled sets h.Enabled and immediately stops any active rumble when disabling.

func (*Haptics) Soft

func (h *Haptics) Soft()

Soft plays a soft impact haptic (core.HapticSoft).

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).

func (*Haptics) Update

func (h *Haptics) Update(dt time.Duration)

Update advances any active rumble or pattern by dt, emitting periodic mobile haptic pulses and ending or advancing steps as their durations expire. Call it from game.Loop.Update.

func (*Haptics) Warning

func (h *Haptics) Warning()

Warning plays a warning outcome haptic (core.HapticWarning).

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

func GamepadButton(b gamepad.Button) Input

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

func Key(name string) Input

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

func KeyCode(code string) Input

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

func TouchRegion(rect core.Bounds) Input

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 natural device X axis (right, in g units).
	TiltX
	// TiltY is device tilt along the natural device Y axis (up, in g units).
	TiltY
	// TiltZ is device tilt along the natural device Z axis (out of the screen, in g units).
	TiltZ
	// GyroX is angular velocity around the natural device X axis (rad/s).
	GyroX
	// GyroY is angular velocity around the natural device Y axis (rad/s).
	GyroY
	// GyroZ is angular velocity around the natural device Z axis (rad/s).
	GyroZ
)

func (MotionAxis) String

func (m MotionAxis) String() string

String returns a stable name for m.

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) and pauses automatically while the app is in background.

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). Updated values are held until the next Step call so reads stay stable within a fixed game.Loop step.

func (*MotionInput) Options

func (m *MotionInput) Options() MotionOptions

Options returns m's current MotionOptions.

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 DeadZone, Sensitivity, TiltRange, GyroRange, Smoothing and OnError at runtime. Changing Sensors or Interval takes effect on the next Start call.

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.

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.

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
	// DeadZone is the default magnitude in [0, 1) below which normalized axis readings snap to 0.
	DeadZone float64
	// Sensitivity multiplies calibrated axis values before clamping (1 when <= 0).
	Sensitivity float64
	// TiltRange is the tilt magnitude in g (9.80665 m/s²) that maps to 1.0 before Sensitivity (1.0 when <= 0).
	TiltRange float64
	// GyroRange is the rotation rate in rad/s that maps to 1.0 before Sensitivity (math.Pi when <= 0).
	GyroRange float64
	// Smoothing is the low-pass filter factor in [0, 1) applied to incoming samples.
	// 0 disables smoothing; higher values smooth more heavily (filtered = prev*Smoothing + raw*(1-Smoothing)).
	Smoothing float64
	// OnError is called on the engine goroutine if WatchMotion's provider reports an error
	// (such as core.SensorNotAllowed or core.SensorNotAvailable).
	OnError func(error)
}

MotionOptions configures a MotionInput watching device sensors via core.Scope.WatchMotion.

type Player

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) Actions

func (p *Player) Actions() *Actions

Actions returns p's Actions, where bindings, axes, virtual pads, and saved controls live. Returns nil if p is nil.

func (*Player) Axis

func (p *Player) Axis(name string) float64

Axis returns the value of axis name in [-1, 1] for p on the current step.

func (*Player) Delta

func (p *Player) Delta(name string) float64

Delta returns the relative motion of pointer axis name for p on the current step.

func (*Player) FallbackActive

func (p *Player) FallbackActive() bool

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

func (p *Player) Gamepad() (gamepad.Pad, bool)

Gamepad returns the latest connected controller state for p's assigned controller, or false when p has no assigned controller or that controller is not currently connected.

func (*Player) GamepadConnected

func (p *Player) GamepadConnected() bool

GamepadConnected reports whether p has an assigned controller that is present in the latest controller snapshot.

func (*Player) GamepadDisconnected

func (p *Player) GamepadDisconnected() bool

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

func (p *Player) GamepadID() (id int, ok bool)

GamepadID returns the controller ID assigned to p and true, or (0, false) when p has no assigned controller.

func (*Player) HasDevice

func (p *Player) HasDevice() bool

HasDevice reports whether at least one physical device (a controller, keyboard, or pointer) is assigned to p.

func (*Player) Index

func (p *Player) Index() int

Index returns p's 0-based slot index in its Players group, or -1 if p is nil.

func (*Player) JustPressed

func (p *Player) JustPressed(name string) bool

JustPressed reports whether action name became pressed for p on the current step.

func (*Player) JustReleased

func (p *Player) JustReleased(name string) bool

JustReleased reports whether action name was released for p on the current step.

func (*Player) Pressed

func (p *Player) Pressed(name string) bool

Pressed reports whether action name is held for p during the current step.

func (*Player) UsesKeyboard

func (p *Player) UsesKeyboard() bool

UsesKeyboard reports whether keyboard events from p's Players group are routed to p.

func (*Player) UsesPointer

func (p *Player) UsesPointer() bool

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

func NewPlayers(count int) *Players

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

func (m *Players) Add() *Player

Add appends a new player slot with an empty Actions and no assigned devices, and returns it.

func (*Players) All

func (m *Players) All() []*Player

All returns a copy of the player slots in index order, or nil when m has no players.

func (*Players) AssignGamepad

func (m *Players) AssignGamepad(index, padID int) bool

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

func (m *Players) AssignKeyboard(index int) bool

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

func (m *Players) AssignPointer(index int) bool

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

func (m *Players) AssignUnassignedGamepads() int

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

func (m *Players) Attach(v *core.View)

Attach wires m's touch, press, mouse, context-menu, pointer-lock motion, and key handlers onto v, chaining any callbacks already set on v. Keyboard events are forwarded to players with AssignKeyboard; pointer and touch events are forwarded to players with AssignPointer.

func (*Players) DisconnectPolicy

func (m *Players) DisconnectPolicy() DisconnectPolicy

DisconnectPolicy returns the disconnect and reconnect policy currently configured on m.

func (*Players) DisconnectedPlayers

func (m *Players) DisconnectedPlayers() []*Player

DisconnectedPlayers returns the player slots currently awaiting controller reconnect, in ascending slot index order, or nil if no player is disconnected.

func (*Players) Gamepads

func (m *Players) Gamepads() []gamepad.Pad

Gamepads returns a copy of the controller state m last read, sorted by controller ID.

func (*Players) Len

func (m *Players) Len() int

Len returns the number of player slots in m.

func (*Players) NextUnassigned

func (m *Players) NextUnassigned() *Player

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

func (m *Players) OnGamepads(pads []gamepad.Pad)

OnGamepads replaces the controller state m reads with pads, such as synthetic or recorded controllers in a unit test or replay, routes each controller to its assigned player, processes any disconnect, reconnect, or press-to-reassign policy transitions, and latches any rising edges so a quick press between steps registers on the next Step.

While WatchGamepads has a live scope attached, the next Step replaces pads with the live controllers.

func (*Players) OnKeyDown

func (m *Players) OnKeyDown(ev core.KeyEvent) bool

OnKeyDown forwards ev to every player assigned to the keyboard and reports whether any of them consumed it.

func (*Players) OnKeyUp

func (m *Players) OnKeyUp(ev core.KeyEvent)

OnKeyUp forwards ev to every player assigned to the keyboard.

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

func (m *Players) OnPointerDelta(dx, dy float64)

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

func (m *Players) PausedByDisconnect() bool

PausedByDisconnect reports whether m has paused gameplay via DisconnectPolicy.PauseOnDisconnect because at least one disconnected player is awaiting a controller without fallback.

func (*Players) Player

func (m *Players) Player(index int) *Player

Player returns the player at slot index, or nil if index is out of range.

func (*Players) PlayerByGamepad

func (m *Players) PlayerByGamepad(padID int) *Player

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) 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) 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) Unassign

func (m *Players) Unassign(index int) bool

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

func (m *Players) UnassignGamepad(index int) bool

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

func (m *Players) UnassignKeyboard(index int) bool

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

func (m *Players) UnassignPointer(index int) bool

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

func (m *Players) UnassignedGamepads() []gamepad.Pad

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

func (m *Players) WatchGamepads(cx *core.Scope)

WatchGamepads makes m poll connected controllers from cx's app once on every Step with gamepad.Pads and route each controller to the player assigned to its ID.

Polling stops once cx is disposed, and while cx's core.Access refuses core.AccessGamepad no controller is read. Passing nil stops watching and releases every controller input across all players.

func (*Players) WatchKeys

func (m *Players) WatchKeys(cx *core.Scope) (stop func())

WatchKeys watches the keys held anywhere on cx's window once and routes them to every player assigned to the keyboard (AssignKeyboard), until cx is disposed, WatchKeys is called again, or stop is called, which releases watched keys on every player.

type PointerAxis

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

type RumbleStep struct {
	LowFreq  float32
	HighFreq float32
	Duration time.Duration
}

RumbleStep is one segment of a rumble or haptic pattern. LowFreq and HighFreq are motor strengths in [0, 1]; setting both to 0 inserts a silent pause for Duration.

type VirtualButton

type VirtualButton struct {
	// Center and Radius define a circular button when Radius > 0.
	Center core.Point
	Radius float32
	// Bounds defines a rectangular button when Radius <= 0.
	Bounds core.Bounds
	// Label is optional text drawn centered inside the button.
	Label string
	// Action is the action name driven by this button in VirtualPad and Actions.
	Action string
	// contains filtered or unexported fields
}

VirtualButton is a circular or rectangular on-screen button with multi-touch finger tracking.

func (*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 label into d, leaving d's state unchanged.

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 at least one finger is currently pressing the button.

func (*VirtualButton) Reset

func (b *VirtualButton) Reset()

Reset releases all fingers tracked by the button.

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
	// contains filtered or unexported fields
}

VirtualPad owns a collection of VirtualSticks and VirtualButtons, routes multi-touch fingers without controls stealing each other's touches, optionally wires into Actions, and draws all controls into a core.Drawing.

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 NewVirtualPad

func NewVirtualPad() *VirtualPad

NewVirtualPad returns an empty VirtualPad.

func (*VirtualPad) AddButton

func (p *VirtualPad) AddButton(b *VirtualButton) *VirtualButton

AddButton adds b to p and returns b.

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 (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 and buttons in p into d.

func (*VirtualPad) OnTouch

func (p *VirtualPad) OnTouch(ev core.TouchEvent)

OnTouch routes ev to p's buttons and sticks so each touch finger stays owned by the control that captured it.

func (*VirtualPad) Pressed

func (p *VirtualPad) Pressed(action string) bool

Pressed reports whether any button in p bound to action is currently pressed.

func (*VirtualPad) Reset

func (p *VirtualPad) Reset()

Reset releases all active sticks, buttons, and 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

	// AxisX and AxisY hold the stick's current normalized outputs in [-1, 1].
	AxisX float64
	AxisY float64
	// contains filtered or unexported fields
}

VirtualStick is a fixed or floating on-screen thumbstick that captures a single touch finger and outputs normalized AxisX and AxisY values in [-1, 1] with radial dead-zone rescaling.

func (*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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL