GitHubComeçar

Esta página ainda não foi traduzida para português, por isso a versão em inglês é exibida abaixo.

Sistemas 2D

a11y

game/a11y provides accessibility building blocks built on NSGo's public API: live dialogue and directional SFX captions, color-blind-safe palettes with CVD simulation and WCAG contrast helpers, persisted assist options, and screen-reader-ready native menus.

For end-to-end wiring with gameui.SettingsMenu, postfx, sound, and input.TouchControls, a guideline-by-guideline map against the Game Accessibility Guidelines and Xbox Accessibility Guidelines, a pre-release checklist, and Apple App Store Accessibility Nutrition Labels, see the Accessibility Guide.

Templates should mount gameui.FirstLaunchSettings before their first sound. It turns captions on by default, persists completion in the shared settings store, and leaves the full Accessibility tab available through More options. Keep the same store connected to a11y.NewAssistFromSettings so captions, reduced motion, flash reduction, text scale, and input assists apply before gameplay begins.

import "github.com/nsgo-dev/game/pkg/a11y"

Persisted assist options (Assist)

NewAssistFromSettings(cx, store) backs *Assist with the game's shared *save.DefaultSettingsStore (save.Settings.Accessibility) so gameui.SettingsMenu, CaptionsView, AccessibleMenu, and postfx.Flash / postfx.Shake stay in sync automatically whenever settings are saved. Wire ApplyAccessibility: assist.ApplySettings on save.SettingsTargets to also preview un-saved SettingsMenu.Apply() edits immediately:

store := save.NewStorageSettingsStore(cx.Storage(), "mygame")
assist := a11y.NewAssistFromSettings(cx, store)

// In game.Loop.Update, scale simulation dt by GameSpeed (0.25..2.0):
loop := &game.Loop{
	Update: func(dt time.Duration) {
		sim.Step(assist.ScaleDT(dt))
	},
}

Any legacy "a11y.assist.*" keys left in cx.Storage() by the deprecated NewAssist(cx, key) constructor are migrated once into store and removed on startup; use MigrateLegacyAssist(cx.Storage(), oldPrefix, store) if migrating a custom legacy prefix. ParseColorVision accepts both "normal" and "none" for VisionNormal.

Available persisted options on *Assist (and snapshot struct AssistOptions via Snapshot() / Apply(opts) / Reset()):

Option Range / Default Notes
GameSpeed / ScaleDT 0.25–2.0 (1.0) Scales gameplay dt without changing display refresh rate.
ReduceMotion bool Defaults to cx.Env().ReduceMotion() when unset; explicit SetReduceMotion(false) overrides the OS.
ReduceFlashes bool Reduces full-screen flashes independently of ReduceMotion: passed to postfx.FlashConfig.ReduceFlashes, it turns them into low-contrast tints.
ScreenShake 0.0–1.0 (1.0) Camera shake intensity multiplier (0 disables shake).
HighContrast bool Defaults to cx.Env().IncreaseContrast() when unset; switches assist.Palette() to VisionHighContrast.
ColorVision ColorVision Selects VisionNormal, VisionProtanopia, VisionDeuteranopia, VisionTritanopia, or VisionHighContrast.
ColorBlindSeverity 0.0–1.0 (1.0) Scales the strength of ColorVisionFilter; defaults to 1.0 when unset.
TextScale 0.5–3.0 (1.0) Defaults to cx.Env().FontScale() (clamped) when unset; multiplier read by CaptionsView and AccessibleMenu.
Invincibility, AutoAim bool Gameplay assist flags for your combat layer.
HoldToToggle bool Convenience switch that fills input.Assists.Toggle from all toggle-eligible actions declared on input.Actions when applied via ApplyToActions / ApplyToPlayers.
InputAssists input.Assists Per-action Toggle and MashToHold lists plus MinPress (slow keys) and AcceptDelay (bounce keys) persisted in save.Settings.InputAssists.
CaptionsEnabled, DialogueCaptionsEnabled, ChatterCaptionsEnabled, SFXCaptionsEnabled bool Master speech captions switch plus per-kind toggles for main dialogue, background chatter, and sound/music cues.
CaptionSettings (CaptionBackground, CaptionBackgroundOpacity, CaptionTextColor, CaptionSpeakerColors, CaptionSize) save.CaptionSettings Player-set caption backdrop color & opacity (0–1), text color, per-speaker name coloring, and size preset (small–xlarge).

When AutoAim is enabled, use input.AimAssist from the fixed-step update. It provides deterministic 2D and 3D friction, magnetism, optional snap, target priorities, and a game-owned line-of-sight callback. Strength is the player-controlled intensity from 0 (off) to 1 (full).

Assist.Reset() resets only save.Settings.Accessibility and save.Settings.InputAssists back to defaults and OS fallbacks, preserving Audio, Display, Bindings, Locale, and Custom sections in the shared store.

Player motor assists

Assist persists input.Assists in save.Settings.InputAssists and bridges both InputAssists and HoldToToggle onto input.Actions (or input.Players) via ApplyToActions / ApplyToPlayers. Wire ApplyInputAssists: assist.ApplyInputAssists on save.SettingsTargets alongside ApplyAccessibility: assist.ApplySettings so gameui.SettingsMenu's Controls tab previews and persists motor assists live:

cx.Effect(func() {
	assist.ApplyToActions(actions)
})

When HoldToToggle() is enabled, ApplyToActions automatically merges actions.ToggleableActions() (from game.yaml assist: {toggle: true} or SetActionAssist) into input.Assists.Toggle, so gameplay hold actions toggle without ever latching menu actions. See input for fixed-step evaluation, pause release, and replay determinism.

Live captions (CaptionTrack & CaptionsView)

Queue timed dialogue (with optional delivery qualifiers), ambient chatter, directional SFX, music cues, and important alerts on a CaptionTrack, step it on game.Loop, and render it as a native NSGo overlay with CaptionsView:

captions := a11y.NewCaptionTrack(cx)

// When an explosion plays to the player's right (direction in [-1, 1]):
if assist.SFXCaptionsEnabled() {
	captions.ShowSFXAt("Explosion", 0.8, 2500*time.Millisecond)
}
captions.ShowDialogueWithQualifier("Guide", "on radio", "Watch the bridge ahead.", 3*time.Second)
captions.ShowChatter("Scout", "Did you hear that?", 2500*time.Millisecond)

// In game.Loop.Update:
captions.Update(dt)

// In your root Stack view:
a11y.CaptionsView(cx, captions, a11y.CaptionStyle{Assist: assist})
  • Formatting & qualifiers: Caption.Format() formats speakers ("Guide: ..."), optional delivery qualifiers ("Guide (on radio): ..."), SFX brackets ("[Explosion]"), directional stereo indicators ("[<] [Explosion]" for left, "[Explosion] [>]" for right, added when |Direction| >= 0.25), important cues ("! ..."), and music cues ("♪ ..."). No directional indicator is added when |Direction| < 0.25. ShowDialogue remembers the last speaker/qualifier and suppresses repeated speaker names until a different speaker/qualifier appears or silence exceeds CaptionTrack.SpeakerRepeatGap (default DefaultSpeakerRepeatGap = 5s; set < 0 to always show speaker names). Dismiss entries early with Dismiss(id) or Clear().
  • Line wrapping & two-line limit: CaptionsView wraps lines at word boundaries (and by character for CJK) to CaptionStyle.MaxChars (default DefaultCaptionMaxChars = 40) and caps total simultaneous visible lines to CaptionStyle.MaxLines (default DefaultCaptionMaxLines = 2), dropping older lines first.
  • Player styling & speaker colors: when CaptionStyle.Assist is set, CaptionsView reads save.CaptionSettings for background color (black, gray, blue, white, or #rrggbb), background opacity (0.0–1.0), text color (white, yellow, cyan, green, black, or #rrggbb), size preset (small, medium, large, xlarge), per-kind filtering (Dialogue, Chatter, Sounds), and per-speaker name coloring (SpeakerColors, using CaptionStyle.SpeakerColors overrides or deterministic CVD-safe colors from PaletteFor).
  • Automatic sources: sound.Effect.SetCaption with CaptionEmitter captions positional sounds in the direction the mixer pans them, without repeating a label within MinInterval (sound), and cutscene.CaptionBridge shows timeline dialogue for as long as each line plays (cutscene).

Customize the live region's accessible name and cue prefixes via CaptionStyle.RegionLabel (default "Captions"), CaptionStyle.ImportantPrefix (default "! "), and CaptionStyle.MusicPrefix (default "♪ "), or fill them from an l10n.Catalog / l10n.Localizer with CaptionStyleFromCatalog / CaptionStyleFromLocalizer.

Mono audio and stereo balance

For players with hearing in one ear, game/sound, game/save, and game/gameui provide mono voice centering and a left/right balance control:

  • save.AudioSettings: Mono (*bool, nil by default to follow the platform's mono audio switch) and Balance (float64 in [-1, 1], 0 centered) persist with player settings and are applied to *sound.Mixer by save.Apply (SettingsTargets.Sound).
  • sound.Mixer: SetMono(bool) / FollowSystemMono() and SetBalance(float32) center every started voice to pan 0 under mono — preserving distance, rear, and cone attenuation — and offset stereo pan by Balance (clamped to [-1, 1]) otherwise. Listener2D.Pan and Listener3D.Pan still return the true spatial direction, so passing that pan to CaptionTrack.ShowSFXAt keeps directional caption cues intact even under mono.
  • gameui.SettingsMenu: the Audio tab includes Mono Audio (System Default / On / Off) and Balance rows wired directly to save.AudioSettings.
  • Current NSGo v0.3.4 limits: stereo audio assets (such as stereo music or ambience tracks) keep their own channels until NSGo supports output down-mixing (nsgo-dev/nsgo#2676), and automatic tracking of the OS mono audio toggle takes effect once NSGo exposes Env.MonoAudio (nsgo-dev/nsgo#2677).

Color-blind palettes, frame filter & CVD preview

PaletteFor(mode) returns an Okabe-Ito / Wong-grounded semantic Palette (Player, Ally, Enemy, Hazard, Pickup, Neutral, Background, Foreground, Highlight, Accent). Use Simulate, SimulateAt, Daltonize, ColorDistance, ContrastRatio, and EnsureContrast in tests or runtime UI theming:

pal := assist.Palette()
simEnemy := a11y.Simulate(pal.Enemy, a11y.VisionDeuteranopia)
ratio := a11y.ContrastRatio(pal.Foreground, pal.Background)
readable := a11y.EnsureContrast(accentColor, pal.Background, 4.5)
_, _, _ = simEnemy, ratio, readable

Whole-frame color-vision filter

Games with hand-authored sprites, tilemaps, and particles that do not read a11y.Palette directly can still honor the player's ColorBlindMode and ColorBlindSeverity (Color-Blind Mode and Color-Blind Strength in gameui.SettingsMenu) by appending a11y.ColorVisionFilter to their postfx.Chain:

if filter, ok := assist.ColorVisionFilter(); ok {
	post = postfx.MustCompile(postfx.VignetteEffect(), filter)
}
  • a11y.ColorVisionFilter(settings) (and assist.ColorVisionFilter()) returns (postfx.Effect, bool) configured for daltonization correction (correct: true) from save.AccessibilitySettings.ColorBlindMode and EffectiveColorBlindSeverity(), or false when the mode is "none" or severity is 0.
  • a11y.ColorVisionSimulation(mode, severity) returns the matching deficiency simulation effect (correct: false) for developer previews and tooling.

Previewing in the editor and testing with gametest

  • Editor: open the Overlays popover in the 2D scene viewport or the Color Vision & Contrast panel beside the text-width table in HUD & menu layout to switch between Normal, Protanopia, Deuteranopia, and Tritanopia. The scene viewport applies postfx.ColorVisionEffect live over the frame, and the HUD layout simulates every device frame and updates each node's WCAG contrast ratio live.
  • Automated tests (pkg/gametest): pass ColorVision on gametest.RenderOptions to render goldens under deficiency simulation (or daltonization with ColorVisionCorrect: true), and assert minimum separation between gameplay-critical colors or rendered screen regions:
sim := gametest.RenderOps(128, 64, ops, gametest.RenderOptions{
	ColorVision: a11y.VisionDeuteranopia,
})
gametest.AssertColorDistinguishable(t, a11y.VisionDeuteranopia, pal.Player, pal.Enemy, 40)
gametest.AssertRegionsDistinguishable(t, frame, heroRect, enemyRect, a11y.VisionProtanopia, 40)
_ = sim

Design guidance: never rely on color alone

A whole-frame filter helps existing art, but do not convey essential gameplay information by color alone (Game Accessibility Guidelines; XAG 103). Pair every color cue with a secondary visual channel — silhouette, icon, pattern, outline, or text label:

  • Match & puzzle tiles (template/puzzle2d): pair each gem or block color with a distinct inner symbol or shape (triangle, diamond, circle, star) so players can match pieces even in monochrome.
  • Units, projectiles & hazards (template/shmup2d, template/towerdefense2d): give player and enemy shots different shapes and sizes (for example, crisp elongated bolts vs. ringed orbs), and distinguish tower or enemy classes by silhouette and status icon rather than tint alone.
  • Cards, meters & pickups (template/cards2d, template/platformer2d): pair suit or rarity colors with suit glyphs, border patterns, and numeric labels, and mark low-health or active states with icons or motion cues in addition to hue changes.

Screen-reader menus (AccessibleMenu)

Set ScanEnabled with ScanInterval to let one switch cycle enabled menu items. The ScanSelectKey key activates the highlighted item, and ScanLoops pauses after a configured number of passes.

Render pause, settings, and assist menus with native ARIA/accessibility roles (RoleMenu, RoleMenuItem, RoleMenuItemCheckbox), full keyboard navigation (Up/Down/Home/End/Return/Space/Escape), and cx.Announce screen-reader feedback:

a11y.AccessibleMenu(cx, a11y.MenuProps{
	Label:   "Assist Options",
	Assist:  assist,
	OnClose: closeMenu,
	Items: []a11y.MenuItem{
		{
			ID:       "reduce-motion",
			Label:    "Reduce Motion",
			Checked:  assist.ReduceMotion,
			OnSelect: func() { _ = assist.SetReduceMotion(!assist.ReduceMotion()) },
		},
		{
			ID:       "game-speed",
			Label:    "Game Speed",
			Value:    func() string { return fmt.Sprintf("%d%%", int(assist.GameSpeed()*100)) },
			OnSelect: cycleGameSpeed,
		},
	},
})

When focus moves to an item whose role natively exposes Checked (RoleMenuItemCheckbox, RoleMenuItemRadio, RoleCheckbox, RoleSwitch, RoleRadio), AccessibleMenu relies on the platform's own checked state instead of repeating the checked/unchecked word; toggle activation and the initial mount announcement still announce the item's state.

Localization (MenuText & l10n)

pkg/a11y ships embedded English (en) and Simplified Chinese (zh) l10n YAML string tables. Load them directly with DefaultCatalog(), or merge them into your game's catalog before loading your own overrides with LoadDefaultCatalog(cat).

Pass MenuText on MenuProps.Text (unset fields inherit from DefaultMenuText()), or build it from an *l10n.Catalog or *l10n.Localizer:

cat := a11y.DefaultCatalog()
loc := l10n.NewLocalizer(cx, cat)
loc.SetLocale("zh-Hans")

capStyle := a11y.CaptionStyleFromLocalizer(loc)
capStyle.Assist = assist

a11y.AccessibleMenu(cx, a11y.MenuProps{
	Label: "辅助选项",
	Text:  a11y.MenuTextFromLocalizer(loc),
	Items: items,
})

Documented l10n keys (also exported as Key* constants):

Key Type Placeholders Default (en)
a11y.menu.defaultLabel string — Menu
a11y.menu.items plural {count} one: {count} item, other: {count} items
a11y.menu.opened string {label}, {items}, {count} {label} opened, {items}
a11y.menu.openedWithItem string {label}, {items}, {count}, {item} {label} opened, {items}. {item}
a11y.menu.position string {item}, {index}, {count} {item}, {index} of {count}
a11y.menu.selected string {label} {label} selected
a11y.menu.closed string {label} {label} closed
a11y.menu.checked string — checked
a11y.menu.unchecked string — unchecked
a11y.menu.on string — On
a11y.menu.off string — Off
a11y.menu.separator string — ,
a11y.captions.regionLabel string — Captions
a11y.captions.importantPrefix string — !
a11y.captions.musicPrefix string — ♪
a11y.captions.bgBlack / bgGray / bgBlue / bgWhite string — Black / Gray / Navy / White
a11y.captions.textWhite / textYellow / textCyan / textGreen / textBlack string — White / Yellow / Cyan / Green / Black
a11y.captions.sizeSmall / sizeMedium / sizeLarge / sizeXLarge string — Small / Medium / Large / Extra Large
a11y.captions.previewSpeaker / previewQualifier / previewDialogue / previewChatterSpeaker / previewChatter / previewSFX string — Sample preview strings (Guide, on radio, Watch the bridge!, Scout, Did you hear that?, Wind howling)

Photosensitivity

Every postfx.Flash runs at most three times in any rolling second, and a saturated-red flash color is desaturated to the gray of its luminance. Share one postfx.FlashLimiter between the full-screen flashes of a screen so that together they stay within three a second, and pass assist.ReduceFlashes to postfx.FlashConfig.ReduceFlashes so that the player's Reduce Flashes setting turns them into low-contrast tints; see postfx.

Text size

gameui roots scale text up to 200% through Root.TextScale and Theme.TextScale. Pass the largest scale the game supports as ScreenCheckOptions.TextScale so CheckScreen reports localized text that overflows only at that size before shipping; see gameui.

Editar esta página