gameui
game/gameui 用於在 core.Drawing 中直接繪製風格化的遊戲內選單與 HUD 控制元件,支援盒式佈局、虛擬解析度縮放、基於動作的 2D 空間焦點導航,以及錨定到 2D 世界座標的原生 NSGo 疊加檢視。
import "github.com/nsgo-dev/game/pkg/gameui"
佈局容器、控制元件與 Root
用佈局容器(Panel、VBox、HBox)和控制元件(Label、Button、Toggle、Slider、List、ProgressBar、Spacer)組裝控制元件樹,再用 Root 包裝:
theme := gameui.DefaultTheme()
resumeBtn := &gameui.Button{Text: "繼續遊戲", OnClick: resumeGame}
volumeSlider := &gameui.Slider{Label: "音量", Min: 0, Max: 1, Value: 0.8, Step: 0.1, OnChange: setVolume}
muteToggle := &gameui.Toggle{Label: "靜音", Style: gameui.ToggleSwitch, OnChange: setMuted}
menu := &gameui.Panel{
Width: 320,
Padding: core.EdgesAll(16),
Child: &gameui.VBox{
Spacing: 10,
Align: gameui.AlignStretch,
Children: []gameui.Widget{
&gameui.Label{Text: "已暫停", TextAlign: core.TextAlignCenter},
resumeBtn,
volumeSlider,
muteToggle,
},
},
}
uiRoot := gameui.NewRoot(menu)
uiRoot.Theme = &theme
在 Canvas.Draw 中呼叫 uiRoot.Draw(d, bounds)(內部自動執行 Layout 並包裹在 Save/Restore 中,不會汙染呼叫方的畫布狀態)。指標與鍵盤事件通過 OnPointerMove、OnPointerDown、OnPointerUp、OnPress 和 OnKeyDown 派發。
可通過 Theme、NineSlice 九宮格邊框(NineSlice.FrameDrawer()、NineSliceStateFrame)以及自定義的 TextDrawer / TextMeasurer 鉤子接入點陣圖字型與自定義皮膚。
虛擬解析度縮放(Viewport)
將 Viewport 賦給 Root.Viewport(或呼叫 Root.DrawWithViewport),即可按固定虛擬解析度排版選單並在各種螢幕比例下穩定縮放:
vp := gameui.NewViewport(1280, 720, gameui.ScaleFit) // ScaleFit、ScaleFill、ScaleStretch、ScaleInteger
vp.LetterboxColor = core.RGB(8, 10, 16)
uiRoot.Viewport = &vp
// 在 Canvas.Draw 中:
vp.SetWindowSize(canvasBounds.Size)
uiRoot.Draw(d, canvasBounds)
Root 會在命中測試時自動通過 Viewport.WindowToVirtual 轉換視窗座標,並在 ScaleFit 或 ScaleInteger 存在留邊時繪製信箱黑邊。
空間動作焦點導航(SpatialNavigator)
面向手柄與鍵盤驅動的網格或多列選單,將 Root 與 SpatialNavigator 搭配使用:
nav := gameui.NewSpatialNavigator(uiRoot)
nav.WrapAround = true
nav.OnBack = closeMenu
nav.SetOverrides(resumeBtn, gameui.NavOverrides{Up: muteToggle})
// 在 game.Loop.Update 中橋接 game/input 動作:
nav.StepActions(func(a gameui.NavAction) bool {
switch a {
case gameui.NavUp:
return actions.JustPressed("ui_up")
case gameui.NavDown:
return actions.JustPressed("ui_down")
case gameui.NavLeft:
return actions.JustPressed("ui_left")
case gameui.NavRight:
return actions.JustPressed("ui_right")
case gameui.NavConfirm:
return actions.JustPressed("ui_confirm")
case gameui.NavBack:
return actions.JustPressed("ui_back")
default:
return false
}
})
通過 Root.FocusRing、Theme.FocusRing 或 SpatialNavigator.FocusRing 上的 FocusRingStyle 可自定義焦點框(包括虛線樣式或自定義 Draw 回撥)。
開箱即用的設定選單(SettingsMenu)
SettingsMenu 提供一套可直接接入的五標籤設定介面,覆蓋 音訊(靜音、主音量與可配置音訊匯流排音量)、影片(視窗/全屏模式、解析度、縮放模式、整數縮放、畫質預設、垂直同步與幀率上限)、控制(支援按鍵與手柄按鍵捕獲和重置的動作改鍵)、語言(地區/語言選擇)以及 無障礙(字幕、文本縮放、高對比度、減少動態效果、螢幕震動、減弱閃爍、色盲模式與遊戲速度)。
選單通過 save.DefaultSettingsStore 持久化玩家設定,並通過 save.SettingsTargets(save.Apply)將校驗後的設定派發到各子系統:
store := save.NewStorageSettingsStore(cx.Storage(), "mygame")
menu := gameui.NewSettingsMenu(gameui.SettingsMenuConfig{
Store: store,
Targets: save.SettingsTargets{
Sound: mixer,
ApplyDisplay: video.Apply,
ApplyBindings: func(b map[string][]string) error { gameui.ApplyBindingsToActions(actions, b, true); return nil },
ApplyLocale: setLocale,
ApplyAccessibility: setAccessibility,
},
OnBack: closeSettings,
})
// 在 Canvas.Draw 中繪製:
menu.Draw(d, bounds)
// 轉發滑鼠、觸控、鍵盤與手柄輸入:
// - 指標:menu.OnPointerMove / OnPointerDown / OnPointerUp / OnPress
// - 觸控:menu.OnTouch(ev)
// - 鍵盤:menu.OnKeyDown(ev)
// - 手柄:menu.StepGamepad(gamepad.Pads(cx))(十字鍵/左搖桿導航,A 確認,B 返回,LB/RB 切換標籤頁,並支援按鍵改鍵捕獲)
- 使用
SettingsResolutionFrom/SetSettingsResolution和SettingsReduceFlashesFrom/SetSettingsReduceFlashes讀寫儲存在save.Settings.Custom中的解析度與減弱閃爍選項。 - 使用
FormatBindingToken、ParseBindingToken、FormatBindingLabel、GamepadButtonToken與ApplyBindingsToActions在save.Settings.Bindings和input.Actions之間雙向轉換。 - 在玩家切換語言後呼叫
SetText傳入翻譯後的SettingsText;未自定義Theme時(或呼叫HighContrastTheme()),開啟Accessibility.HighContrast會自動切換到高對比度配色。 - 開啟選單時呼叫
SyncGamepad,避免用於開啟設定介面的按鍵按住狀態在選單內立即觸發。
世界座標錨定原生檢視(AnchorOverlay)
使用 AnchorOverlay 將普通原生 NSGo 檢視(頭頂名牌、對話氣泡、聊天輸入框)釘在遊戲畫布上的 2D 世界位置:
overlay := gameui.NewAnchorOverlay(cx)
overlay.Add(&gameui.WorldAnchor{
ID: "npc-1",
WorldX: 240,
WorldY: 120,
OffsetY: -28,
AnchorX: 0.5,
AnchorY: 1,
Visible: true,
View: func(cx *core.Scope) core.View {
return core.Text(cx, "鐵匠")
},
})
// 每幀相機更新後同步:
proj := gameui.NewCameraViewportProjection(cam.X, cam.Y, cam.Zoom, 1280, 720, vp)
overlay.Sync(proj)
在 core.Stack 中將 overlay.View(cx) 疊放在遊戲 Canvas 之上即可。投射到 ScreenBounds 之外的錨點會自動隱藏,位置通過 SetWorldPosition 與 Sync 更新而無需重建外層檢視樹。
介面螢幕檔案(*.screen.yaml)
可將 HUD 與選單編寫為帶版本號的純文本 YAML 檔案(*.screen.yaml,已釋出 Schema 為 https://game.nsgo.dev/schemas/screen.v1.json),而不必在 Go 程式碼中手寫所有控制元件。ParseScreen、LoadScreenFS 與 EncodeScreen 會拒絕未知欄位、重複的節點 ID 或焦點順序、YAML 錨點/別名以及不支援的版本號,並以規範的 2 空格縮排 YAML 無損往返。
螢幕檔案宣告 designWidth × designHeight 設計畫布尺寸(例如 640 × 360)、可選的 scaleMode(fit、fill、stretch、integer)以及節點樹(vbox、hbox、label、button、sprite_row、color_rect、touch_stick、touch_button、container):
- 錨點與安全區:通過
anchor指定九宮格錨點(top_left、top_center、top_right、center_left、center、center_right、bottom_left、bottom_center、bottom_right)或fill,通過offset(右側/底部錨點的正值向內縮排)設定偏移,並用safeArea控制是否保持在安全區內(非fill預設為true,fill預設為false)。 - 尺寸與本地化文本:在
textKey中存放本地化鍵而非字面文本,使用sizeMode: fixed搭配width或sizeMode: fit_text隨翻譯文本自適應寬度,並支援padding、spacing、fontSize、textColor、background與cornerRadius。 - 焦點順序、觸控熱區與裝置類別:使用從 1 開始的
focusOrder宣告鍵盤/手柄焦點遍歷順序,使用touchHitSize設定擴充套件圓形觸控熱區(TouchButton、TouchStick、Button),並使用deviceClasses(phone、tablet、desktop、ultrawide)按裝置類別條件顯示控制元件。
執行時呼叫 BuildScreen 將螢幕檔案構建為 gameui.Root 與 SpatialNavigator:
doc, err := gameui.LoadScreenFS(assetsFS, "screens/hud.screen.yaml")
if err != nil {
return err
}
phone := gameui.ReferenceDevicesFor(doc.DesignWidth, doc.DesignHeight)[0]
screen, err := gameui.BuildScreen(doc, gameui.ScreenBuildOptions{
SafeArea: phone.SafeArea,
DeviceClass: phone.Class,
ViewportWidth: phone.Width,
ViewportHeight: phone.Height,
Catalog: catalog,
Locale: "zh",
OnClick: map[string]func(){
"pause_button": openPauseMenu,
"jump": triggerJump,
},
})
在 Canvas.Draw 中呼叫 screen.Draw(d, bounds),並可通過 screen.ApplyCatalog(catalog, locale) 動態切換語言、通過 screen.SetSafeArea(insets) 更新安全區邊距、通過 screen.SetDeviceClass(class) 切換裝置類別過濾。
靜態檢查(game check)與安全重構(refs、game mv)
game check(及 gameui.CheckScreen)會檢查專案中的所有 *.screen.yaml 檔案,並按檔案、行號和節點 ID 報告以下問題:
- 手機和平板上的觸控熱區小於
44 pt; - 本地化文本(含全形中文字元寬度)在四個參考尺寸(
Phone 19.5:9 (notch)、Tablet 4:3、Desktop 16:9、Ultrawide 21:9)下超出固定框或安全區; textKey在專案的任意語言字串表中缺失;- 文本與其填充背景的 WCAG 對比度低於
4.5:1; - 引用的
sprite圖片或圖集幀缺失。
refs 與 game mv 會追蹤 *.screen.yaml 中的 sprite 路徑和 textKey 引用:game mv art/heart.png art/ui/heart.png 會原地更新 sprite:,而 game mv -text-key hud.hint.lever hud.tip.lever 會同步重新命名所有 *.screen.yaml 與 YAML 本地化字串表中的鍵。