이 페이지는 아직 한국어로 번역되지 않아 영문 원문을 표시하고 있습니다.
2D 코어Loop
game.Loop drives fixed-step updates and interpolated frame draws on an NSGo scope's display frames, pausing automatically while the app is in the background.
import "github.com/nsgo-dev/game"
How the fixed step works
Displays run at different refresh rates (60 Hz, 90 Hz, 120 Hz, or variable). If a game moves physics by raw frame delta times, jump heights and collisions change with the display rate.
Loop decouples simulation from rendering:
type Loop struct {
Rate int // updates a second, 60 when 0
MaxSteps int // most updates one frame runs, max(1, Rate/10) when 0
Paused bool // stops Update from advancing with display time
PausedAwake time.Duration // how long to keep the display awake while paused or OnDemand-idle
TimeScale float64 // simulated time multiplier, 1 when <= 0 or non-finite
DrawRate int // caps Draw calls per second, uncapped when <= 0
MatchDisplayToRate bool // asks the display to use Rate when DrawRate is uncapped
OnDemand bool // skips Draw on frames without Update unless MarkDirty was called
Idle func() bool // with OnDemand, skips both Update and Draw while returning true
Immersive bool // hides phone system bars while unpaused
Update func(dt time.Duration) // moves the game on by dt, always 1/Rate seconds
Draw func(alpha float64) // draws the frame, alpha in [0, 1)
FrameTime func(dt time.Duration) // receives each frame's length before updates
OnPause func(paused bool) // runs whenever Paused changes
}
func (l *Loop) Run(cx *core.Scope) (stop func())
func (l *Loop) SetPaused(paused bool)
func (l *Loop) SetTimeScale(scale float64)
func (l *Loop) Step(n int)
func (l *Loop) StepOnce()
func (l *Loop) StepNow(n int) int
func (l *Loop) MarkDirty()
On each display frame from NSGo's RequestAnimationFrame:
- The loop adds the elapsed time since the previous frame to an accumulator.
- While the accumulator holds at least one whole step (
time.Second / time.Duration(Rate)), it subtracts one step and callsUpdate(step). A single display frame may run zero, one or several updates. - Once fewer than one whole step remains, it calls
Draw(alpha)withalpha = float64(acc) / float64(step)in[0, 1).
Run reads Rate, MaxSteps, Update and Draw on every frame, so you can swap handlers or adjust the rate while the loop is running.
Interpolating with alpha
When the display rate does not evenly divide Rate (for example, a 60 Hz simulation on a 120 Hz display), drawing the raw state from Update produces visible stutter because some frames run zero updates and some run one.
Keep the previous and current state in Update, pass alpha into a core.Signal[float64] from Draw, and interpolate inside core.Canvas.Draw:
func Ball(cx *core.Scope) core.Node {
var x, last float32
alpha := core.NewSignal(cx, 0.0)
loop := &game.Loop{
Rate: 60,
Update: func(dt time.Duration) {
last = x
x += 120 * float32(dt.Seconds())
},
Draw: func(a float64) {
alpha.Set(a)
},
}
loop.Run(cx)
return core.Canvas{
Style: core.Style{FlexGrow: 1, FlexShrink: 1},
Draw: func(d *core.Drawing, _ core.Size) {
at := last + (x-last)*float32(alpha.Get())
d.SetFillColor(core.RGB(0xff5a1f)).FillRect(at, 40, 16, 16)
},
}
}
Because alpha is read only inside Canvas.Draw, setting it redraws the canvas without re-evaluating or committing the surrounding view tree.
Hitch protection and MaxSteps
If a single frame takes much longer than usual (a debugger pause, a slow frame, or a device stall), catching up every missed step would cause an even slower next frame — the classic "spiral of death".
MaxSteps caps how many Update calls one display frame may execute:
- When
MaxSteps <= 0, it defaults tomax(1, Rate/10)— one tenth of a second of simulation (6 steps at 60 Hz, 12 steps at 120 Hz). - When a frame reaches
MaxSteps, the loop drops the remaining whole steps (acc %= step) and moves straight toDraw. The game briefly slows down instead of freezing.
Set MaxSteps explicitly when you need a tighter bound (for example, MaxSteps: 3 for heavy physics):
loop := &game.Loop{
Rate: 60,
MaxSteps: 3,
Update: stepWorld,
Draw: renderWorld,
}
Frame time
Each frame adds the time between its timestamp and the previous frame's, exactly as RequestAnimationFrame gives it. Where the platform stamps its display frames, that is the display's own frame time, so a frame's length is the display's rather than when the engine got to the frame; elsewhere it is the graph clock's. The first frame after the loop starts or resumes adds the time from then to its timestamp, which may lie a frame ahead where the display stamps a frame with when it will show, so the loop's time is the shown frame's. A frame stamped before the time the loop started or resumed adds nothing, so resuming never moves the accumulator backward, and the next frame adds the time from then.
Set FrameTime to read each frame's length, the time it adds, ahead of the frame's updates; a frame that adds nothing passes 0. Frame-time statistics, such as quality's Selector, read it. The first frame back from the background measures from the time the window showed again, not the time away, and FrameTime may call the stop function Run returned, which ends the frame before any update. It also fires while Paused is set, so a caller that should only measure frames that simulate skips them itself.
loop := &game.Loop{
FrameTime: func(dt time.Duration) { selector.Observe(dt) },
Update: stepWorld,
Draw: renderWorld,
}
Pausing and syncing subsystems
SetPaused(true) (or setting Paused = true) stops Update from advancing while Draw keeps running, and unpausing resumes without a catch-up backlog. Set OnPause to keep subsystems such as sound.Mixer in sync with the loop's paused state:
mixer.SetPauseExempt("ui", true)
loop := &game.Loop{
Rate: 60,
OnPause: mixer.SetPaused,
Update: stepWorld,
Draw: renderWorld,
}
loop.Run(cx)
SetPausedcallsOnPauseimmediately whenever the paused state changes (repeating the same value does nothing).- Editing
Pauseddirectly callsOnPauseon the next frame, or in the same frame whenUpdatechanges it. - If
Pausedis alreadytruewhenRunstarts,RuncallsOnPause(true). - Backgrounding does not call
OnPause; bothLoop.Runandsound.NewMixerwatchcore.Env.Lifecycledirectly so backgrounding pauses and resumes everything in sync without clearing an open pause menu.
Scaling time (TimeScale)
TimeScale (or SetTimeScale) scales simulated time for slow-motion effects or fast-forward without changing the fixed dt passed to Update:
0.5runs half as manyUpdatesteps per second;2.0runs twice as many (still capped byMaxStepsper frame).- Values at or below
0(as well asNaNand±Inf) default to1.
loop.SetTimeScale(0.25) // bullet-time slow motion; Update still sees dt == 1/Rate
Single-stepping while paused (Step, StepOnce, StepNow)
While Paused is true, you can advance the simulation by an exact number of fixed steps without unpausing:
Step(n)queuesnfixedUpdatesteps to run on the next display frame, followed by aDraw(0)(non-positive values do nothing).StepOnce()is shorthand forStep(1).StepNow(n)runsnfixedUpdatesteps and aDrawsynchronously right away (whetherPausedistrueorfalse) and returns how many steps ran, which suits deterministic tests and editor replay tools.
Capping the draw rate (DrawRate)
Set DrawRate to cap how many times Draw runs per second while keeping Update at Rate (for example, 60 Hz physics with 30 fps rendering under low-power mode). Values at or below 0 leave Draw uncapped at the display's refresh rate.
When OnDemand and DrawRate are both set, a MarkDirty request that arrives before the next draw interval is preserved and drawn once the interval elapses.
Matching the display rate (MatchDisplayToRate)
Loop asks the host to lower the display refresh rate when it can. A positive DrawRate becomes the preferred display rate, so a low-power cap avoids waking the app at the panel's full rate. Set MatchDisplayToRate: true when DrawRate is uncapped and the display should follow the fixed update rate. Paused loops and idle OnDemand loops request a conservative 60 Hz idle rate, which lowers wakeups on high-refresh panels while preserving the usual cadence on 60 Hz displays. The host may choose a different supported rate.
On-demand drawing and idling (OnDemand, Idle, MarkDirty)
Menu-heavy, turn-based and narrative games often sit waiting for the player to tap or press a key. Set OnDemand: true together with Idle so the loop does zero update and draw work while nothing is animating:
- Without
Idle:OnDemand: trueskipsDrawon frames where noUpdateran unlessMarkDirty()was called (for example, a 30 Hz simulation on a 60 Hz display draws 30 times a second, and aPaused: trueloop draws only onSteporMarkDirty). - With
Idle: whileOnDemandistrue,PausedisfalseandIdle()returnstrue, the loop skips bothUpdateandDrawon display frames without accumulating elapsed time (so waking later produces no catch-up backlog). - Waking on input (
MarkDirty): callingMarkDirty()requests aDrawon the next frame; when an unpausedOnDemandloop is idle,MarkDirty()also queues one fixedUpdatestep on that frame soUpdatecan sample input and advance state. MultipleMarkDirty()calls between frames coalesce into a single wake step. If thatUpdatestarts ongoing work (soIdle()returnsfalse), fixed-step updates resume normally untilIdle()returnstrueagain. - Wiring input: assign
actions.Wake = loop.MarkDirtyoninput.Actions(andTouchControls.OnWakeorGestureRecognizer.Wakewhen used without a boundActions), and callloop.MarkDirty()from view callbacks (such as buttonOnPress) that mutate state outsideUpdate.
loop := &game.Loop{
Rate: 60,
OnDemand: true,
Idle: func() bool {
return fadeLeft == 0 && typewriter.Done() && !autoMode
},
Update: func(dt time.Duration) {
actions.Step()
handleInput()
stepAnimations(dt)
},
Draw: func(float64) {
frame.Update(func(v uint64) uint64 { return v + 1 })
},
}
actions.Wake = loop.MarkDirty
loop.Run(cx)
Background pause and stopping
Loop.Run watches cx.Env().Lifecycle():
core.LifecycleBackground(minimized, hidden or covered on desktop; app backgrounded on iOS or Android): the loop cancels its pending frame request and runs no updates.core.LifecycleActiveorcore.LifecycleInactive(visible, even without focus on desktop): the loop runs normally. When returning from the background, it resets its clock anchor tocx.Now(), so time spent away produces zero catch-up steps.- Set
PauseOnLeave: LeaveInactiveto pause once on any focus loss, orLeaveBackgroundto pause only when the app is backgrounded. The pause stays set untilSetPaused(false)is called.OnLeaveruns once for every transition away from the active lifecycle and receives whether the transition was backgrounding, which is a suitable place to save progress. The signals it reads do not subscribe the loop, so a change to them never calls it again. - A live run also calls
OnLeaveduring scope quit when it has not already handled the current background transition. The stop function returned byRunends that run’s lifecycle and quit callbacks. - The
shmup2dtemplate pauses a running game on focus loss or backgrounding. The pause menu stays open until the player chooses Resume.
The loop ends permanently when either:
- The
cxscope is disposed (for example, navigating away or hiding the component withcore.Show), or - You call the
stopfunction returned byRun.
Calling stop() is safe to repeat and safe from inside Update: if Update stops the loop, no further updates and no Draw run for that frame, and returning from the background will not restart it.
var stop func()
loop := &game.Loop{
Update: func(dt time.Duration) {
if gameOver {
stop()
}
},
Draw: func(alpha float64) {
frame.Set(alpha)
},
}
stop = loop.Run(cx)
Keeping the display awake
While the loop runs in the foreground and is active (not Paused, and not idle under OnDemand and Idle), Loop.Run holds a display keep-awake lock (core.Scope.KeepAwake with Display: true) so the device does not dim or auto-lock mid-game:
- Background,
stop, or scope disposal: the display hold is released immediately. - Paused or idle
OnDemandloops: once the loop isPausedorOnDemand-idle (Idle()returnstrue, with no pendingStepupdates orMarkDirtywake/draw), the hold is released afterPausedAwake. The default0(or any non-positive value) releases the hold immediately so the OS auto-lock timer runs normally on pause, title, waiting-dialogue, and game-over screens. - Grace period (
PausedAwake): setPausedAwake(for example30 * time.Second) to keep the display awake briefly after pausing, going idle, or after the lastStep/MarkDirtybefore releasing the hold. - Resuming and stepping: calling
SetPaused(false)takes the hold again immediately (changingPaused = falsedirectly or havingIdle()returnfalsetakes it on the next frame). QueuingStepupdates while paused or callingMarkDirtyon a paused or idleOnDemandloop keeps the hold while those updates or draws run and resets thePausedAwaketimer. - Cutscenes:
cutscene.Playertakes its own display hold while a cutscene plays, so pausing the game loop underneath a cutscene does not let the screen sleep.
loop := &game.Loop{
Rate: 60,
PausedAwake: 30 * time.Second, // optional grace period on pause menus
Update: stepWorld,
Draw: renderWorld,
}
loop.Run(cx)
Immersive mode on phones
Set Immersive to hide a phone's system bars while the game plays and bring them back in menus. The loop calls NSGo's mobile.Immersive: Android hides its status and navigation bars and shows them briefly on an edge swipe, iOS hides the status bar and lets the home indicator fade, and HarmonyOS hides its status bar, navigation bar and navigation indicator. Desktop and web targets ignore it.
loop := &game.Loop{
Immersive: true,
Update: stepWorld,
Draw: renderWorld,
}
loop.Run(cx)
// Opening the pause menu shows the bars on the next frame; closing it hides them again.
openMenu := func() { loop.SetPaused(true) }
closeMenu := func() { loop.SetPaused(false) }
- The bars hide while the loop runs and is not
Paused, and come back while it isPaused, whenstopis called and whencxis disposed, so a menu screen that replaces the game's view brings them back too. - The loop hides them as it starts or returns from the background, applies a change to
ImmersiveorPausedon its next frame (in the same frame whenUpdatepauses), and asks the platform only when the state changes. It leaves the bars as they are while the app is in the background. - Hiding and showing the bars can change the safe-area insets the platform reports (HarmonyOS, for one, keeps only the display cutout while they are hidden), so lay HUDs out with
screen.Viewport.SafeGameRectForEnv, which follows the insets as they change. - Loops in the same window share the bars: they stay hidden while any loop with
Immersiveset plays, and come back once the last of them pauses or ends. A scene that starts its own loop while the previous scene's loop is still alive, as under a scene transition, keeps the bars hidden when the old loop is disposed, and a pushed scene's loop keeps them hidden when the scene below pauses its own. A menu shown as an NSGo page or dialog can also setStatusBar: core.StatusBarSetting{Immersive: core.ToggleOff}, which overrides the window's setting while it is shown.
Testing with nsgotest
nsgotest runs display frames deterministically on a virtual clock (one frame every 16.667 ms, 60 frames a second), so you can test gameplay loops, MaxSteps hitches and background pauses without sleeping.
package mygame_test
import (
"testing"
"time"
"github.com/nsgo-dev/game"
"github.com/nsgo-dev/nsgo/core"
"github.com/nsgo-dev/nsgo/nsgotest"
)
func TestMain(m *testing.M) { nsgotest.Main(m) }
func TestLoopSimulation(t *testing.T) {
updates := 0
l := &game.Loop{
Rate: 60,
MaxSteps: 4,
Update: func(dt time.Duration) {
updates++
},
}
app := nsgotest.Start(t, func(cx *core.Scope) core.Node {
l.Run(cx)
return core.View{}
})
// Advance steps frame by frame for one full second.
app.Advance(time.Second)
if updates != 60 {
t.Fatalf("got %d updates, want 60", updates)
}
// FastForward jumps in a single frame, exercising MaxSteps.
app.FastForward(500 * time.Millisecond)
if updates != 64 {
t.Fatalf("got %d updates after hitch, want 64", updates)
}
// Background pauses the loop with no catch-up on resume.
app.SetEnvironment(core.Environment{Lifecycle: core.LifecycleBackground})
app.Advance(time.Second)
app.SetEnvironment(core.Environment{Lifecycle: core.LifecycleActive})
if updates != 64 {
t.Fatalf("got %d updates while backgrounded, want 64", updates)
}
}
Guarding unsaved progress on quit
save.QuitGuard centralizes the decision used by close and quit adapters: a clean request closes, an ordinary request with unsaved progress saves first when the game can save now (QuitSave) and asks the player otherwise (QuitAsk), and a forced shutdown saves best effort with SaveForced and closes even when saving fails (QuitSaveAndAllow). See Unsaved progress on close.
Register gameui.GuardQuit once in the game's window scope with a gameui.QuitGuardOptions. The adapter handles both system Quit and the window close button, including the close button on macOS. Ask opens the game's confirmation UI. Call its answer with true to close or false to keep playing, on the same scope. Use Pause to suspend simulation while the question is open and combine that pause with the game's existing pause state. Report can display or log a save error. A failed ordinary save falls back to confirmation and a forced quit proceeds after a best-effort save.
Mount gameui.QuitConfirmation alongside the game view. Give its Open the signal set by Pause and forward OnAnswer to the reply from Ask. The dialog initially focuses Cancel. Set Save to offer Save and quit, and optionally CanSave to control when the action is available. A failed save keeps the dialog open for retry. To use a controller, call gamepad.EnableFocusNavigation on the window scope and release any gameplay input capture while the question is open. For Restart or Quit to title, supply the action's own copy and handle OnAnswer directly.
Loop.PauseOnLeave and HandleLeave provide a shared leave-policy hook for pausing and save callbacks when a game loses focus or backgrounds.
Fixed-step interpolation
tilemap.Camera keeps its previous fixed-step pose: call BeginStep before each Update that moves it, ResetInterpolation after a teleport or a cut, and InterpolatedPose(alpha) in Draw for the position and rotation to draw (rotation turns along the shortest arc; Zoom is not interpolated). It never changes the camera, so simulation state stays the same. Physics bodies and scene objects keep no previous pose yet; interpolate them by hand as in Interpolating with alpha.