Esta página aún no está traducida al español, por lo que se muestra la versión en inglés.
Núcleo 2Dscene
game/scene composes ordered world- and screen-space layers, hit-tests sprites and custom drawables in view coordinates, and manages scene lifecycles, overlay stacks, and animated transitions.
import "github.com/nsgo-dev/game/pkg/scene"
Scene, layers, and drawables
A Scene holds a shared *tilemap.Camera and a slice of *Layer values drawn in stable ascending Order. Each layer operates in either SpaceWorld (drawn under Scene.Camera) or SpaceScreen (drawn directly in view space for HUD elements):
sc := scene.NewScene(cam)
terrain := sc.AddLayer(scene.NewLayer("terrain", scene.SpaceWorld, 0))
terrain.AddTilemap(levelMap)
actors := sc.AddLayer(scene.NewLayer("actors", scene.SpaceWorld, 10))
actors.AddBatch(actorBatch)
hud := sc.AddLayer(scene.NewLayer("hud", scene.SpaceScreen, 100))
hud.AddDrawable(scene.NewDrawable(func(d *core.Drawing) {
drawMinimap(d)
}))
- Items: a layer accepts
AddTilemap,AddTileLayer,AddBatch,AddDrawable, or an explicitAddItem(scene.Item{...}). Items inside a layer draw in stable ascendingZ. - Parallax & repeat:
SpaceWorldlayers supportParallaxX/ParallaxYscroll factors (0 pins a layer against camera translation, 0.5 scrolls at half speed, 1.0 matches the camera, >1.0 scrolls faster for foregrounds; start withscene.NewParallaxLayerorLayer.SetParallax),OffsetX/OffsetY, and seamless tiling viaRepeatX/RepeatYwithRepeatWidth/RepeatHeight. YAML scenes (game/sceneformatversion 3) exposeparallaxX,parallaxY,repeatX,repeatY,repeatWidth, andrepeatHeightwith identical camera semantics (Editor & Scene Format). - Y-sorting (
DepthSort = scene.SortY): sorts sprites, customDrawables, and tiles from anytilemap.TileLayerwithYSort: truein one stable painter's-order list by ascending Y (with optionalSortKey/SpriteSortKeyoverrides and per-tilesort_origin_yoffsets). Non-Y-sorted tilemap layers before Y-sorted layers draw behind sprites, and trailing non-Y-sorted layers (such as roofs) draw above them; useAddTileLayer(m, layer)to bind a single tile layer to a specific scene layer. Drawable: wraps customDraw,Update,Hit,OnPress, andOnTouchhooks with its ownZandVisibleflag. Its zero value hasVisible: false; start withscene.NewDrawable(fn).Scene.Update(dt)advancesCamera, tilemaps, and custom drawables in layer order;Scene.Draw(d)draws every visible layer while preservingd's transform and paint state.
Hit testing and input dispatch
Scene.HitTest(p) tests view-space point p in reverse draw order (highest Layer.Order, then highest item/sprite Z), converting p via Camera.ViewToWorld on SpaceWorld layers and testing p directly on SpaceScreen layers:
if hit, ok := sc.HitTest(ev.Position); ok {
if hit.Sprite != nil {
selectUnit(hit.Sprite, hit.Point)
}
}
Use HitTestAll(p) to retrieve every overlapping target from topmost to bottommost.
Custom hit shapes and callbacks
By default, sprites hit-test against their transformed untrimmed frame bounds (SpriteContains / SpriteToLocal). Override hit geometry or attach direct press/touch handlers with SetSpriteHit (and remove with ClearSpriteHit):
sc.SetSpriteHit(&coinSprite, scene.HitOptions{
Hit: scene.SpriteLocalHit(&coinSprite, scene.CircleHit(core.Point{X: 8, Y: 8}, 7)),
OnPress: func(hit scene.HitResult, ev core.PressEvent) {
collectCoin()
},
})
Built-in HitFunc helpers: RectHit(bounds), CircleHit(center, radius), PolygonHit(vertices...), and SpriteLocalHit(sp, local). Set HitOptions{Ignore: true} to make a decorative sprite transparent to clicks and touches.
Route view events directly to the topmost hit target with sc.DispatchPress(ev) and sc.DispatchTouch(ev) (when a target sets OnPress without OnTouch, DispatchTouch falls back to OnPress on TouchStart).
Manager, stacks, and transitions
Manager owns a stack of *Controller scenes under a parent *core.Scope. Every entered scene receives its own child *core.Scope in Enter(cx), so loops, signals, timers, and audio created under cx are automatically disposed when the scene exits:
mgr := scene.NewManager(cx)
play := &scene.Controller{
Scene: gameScene,
Enter: func(scx *core.Scope) {
// Resources owned by this scene's child scope
startLevelMusic(scx)
},
Pause: func() { pauseSimulation() },
Resume: func() { resumeSimulation() },
Exit: func() { cleanupLevel() },
Update: func(dt time.Duration) {
gameScene.Update(dt)
},
}
pauseMenu := &scene.Controller{
Scene: pauseScene,
Transparent: true, // draws the paused scene underneath
}
mgr.Switch(play, scene.Fade(400*time.Millisecond, core.RGB(0x000000)))
// Later, push an overlay without exiting play:
mgr.Push(pauseMenu)
// Pop to resume play:
mgr.Pop()
Transitions
Pass a *Transition to mgr.Switch(next, tr):
| Helper | Visual behavior |
|---|---|
Fade(d, color) |
Fades outgoing scene to color over the first half, then reveals incoming scene over the second half (crossfades when color is transparent/0). |
Crossfade(d) |
Crossfades directly from outgoing to incoming scene over d. |
Wipe(d, dir) |
Clips scenes along an edge moving in DirectionLeft, DirectionRight, DirectionUp, or DirectionDown. |
CustomTransition(d, draw) |
Calls your custom draw function with eased progress in [0, 1] plus drawOld and drawNew. |
Set tr.Curve to any core.Curve easing function. While a transition runs (mgr.Transitioning()), the incoming scene enters immediately while the outgoing scene stays alive to render until completion, then exits and disposes its child scope.
Drive the manager from your game.Loop and core.Canvas:
// In Loop.Update:
mgr.Update(dt)
// In Canvas.Draw (automatically subscribes to scene changes & transitions):
mgr.Draw(d, size, alpha.Get())
2D layers over a 3D view (Overlay3D)
Overlay3D renders 2D screen-space layers (SpaceScreen), standalone *sprite.Batches, and custom draw callbacks in a transparent core.Canvas stacked directly over a 3D gpu.View (and beneath any native NSGo HUD views in gpu.ViewProps.Children):
ov := scene.NewOverlay3D(cx)
ov.Scene = hudScene // draws visible SpaceScreen layers (SpaceWorld layers are skipped)
ov.AddLayer(crosshair) // extra 2D layers merged by stable ascending Layer.Order
ov.AddBatch(markerBatch) // standalone sprite batches drawn over the layers
ov.Viewport = &screen.Viewport{Width: 320, Height: 180, Mode: screen.ModeFit}
// Mount directly over a 3D gpu.View:
return ov.View(cx, gpu.ViewProps{
DepthFormat: gpu.FormatDepth24Plus,
OnReady: onReady,
OnFrame: onFrame,
Children: nativeHUDViews, // rendered above the 2D overlay canvas
})
- Draw order: visible
SpaceScreenlayers fromSceneand visibleLayersmerge in stable ascendingLayer.Order, followed byBatchesin slice order andOnDraw(wrapped inSave/Restore). CallScene.DrawScreenLayers(d)directly if you manage your own canvas. - Transparency & virtual viewports: the overlay canvas has no background fill so transparent regions reveal the 3D scene underneath and semi-transparent sprites alpha-blend over it. When
Viewportis set with a zeroBarColor, letterbox and pillarbox margins stay transparent instead of painting opaque black bars over the 3D view; setBarColorexplicitly (such ascore.RGB(0x000000)) to draw bars. - Pointer pass-through & hit testing: by default the overlay canvas sets
core.PointerEventsNoneso clicks and touches pass straight through to the 3Dgpu.View. SetInteractive: true(orOnPress) to handle pointer events directly on the overlay canvas, or callov.HitTest,ov.HitTestAll,ov.DispatchPress, andov.DispatchTouchmanually with the view size. - 3D-to-2D projection: map a 3D world position through a column-major view-projection matrix (such as
cam.ViewProj()fromgame/scene3d) into 2D overlay coordinates withscene.ProjectToOverlay(cam.ViewProj(), p.X, p.Y, p.Z, viewW, viewH)(orov.Project(cam.ViewProj(), p.X, p.Y, p.Z, windowSize)to convert intoov.Viewport's virtual coordinates) so 2D health bars, reticles, and markers track 3D objects accurately. Callov.Invalidate()(orov.SetHidden(bool)) whenever dynamic 2D overlay state changes.
Native HUD over a 3D view (HUD3D)
HUD3D composes native NSGo views (ui.Button, ui.Card, ui.Badge, ui.Progress, ui.Switch, core.Text, and custom core.View trees) over a 3D gpu.View with automatic safe-area insets, reactive visibility toggling, and mouse/touch pass-through:
hud := scene.NewHUD3D(cx)
hud.Padding = core.All(12)
// Decorative readout: mouse and touch pass straight through to the 3D scene.
hud.AddPassThrough(scene.HUDTopLeft, ui.Badge{Text: "HP 100"})
// Interactive controls anchored to safe-area corners:
hud.AddAt(scene.HUDTopRight, ui.Button{
Text: "Pause",
OnPress: togglePause,
})
hud.AddAt(scene.HUDBottomRight, ui.Button{
Text: "Jump",
OnPress: triggerJump,
})
// Mount directly over a 3D gpu.View:
return hud.View(cx, gpu.ViewProps{
DepthFormat: gpu.FormatDepth24Plus,
OnReady: onReady,
OnFrame: onFrame,
OnPress: pick3DObject,
})
- Mouse and touch pass-through: the HUD overlay container uses
core.PointerEventsBoxNoneso interactive HUD controls handle clicks and touches directly while open regions pass mouse and touch events unobstructed to the 3D view underneath. Mark decorative elements (such as crosshairs or score readouts) withAddPassThrough(orHUDSlot{PassThrough: true}) to applycore.PointerEventsNone. - Anchors & custom layouts: place widgets with
AddAt/AddPassThrough/AddSlotat any of the 9 safe-area anchors (HUDTopLeft,HUDTopCenter,HUDTopRight,HUDCenterLeft,HUDCenter,HUDCenterRight,HUDBottomLeft,HUDBottomCenter,HUDBottomRight) orHUDFull, or add custom pass-through containers directly withAdd/Children. - Safe-area insets:
core.EnvSafeAreapadding is applied automatically (combined withHUD3D.Padding) so HUD controls stay clear of notches, status bars, and home indicators and adapt reactively on rotation. SetIgnoreSafeArea: trueor callhud.SetSafeArea(false)to disable it. - Visibility toggle: call
hud.SetHidden(true),hud.SetVisible(false), orhud.Toggle()to hide the HUD (core.DisplayNone+core.PointerEventsNone) without remounting HUD state; while hidden, all clicks and touches reach the 3D view. - Composing with 3D input wrappers or 2D overlays: use
hud.Wrap(cx, view3D)to Z-stack the HUD as a sibling over any already-built 3D view (for example agpu.Viewwrapped in acore.ViewhandlingOnMouseDown,OnMouseMove, andOnTouchfor 3D camera orbit), or mounthud.Layer(cx)directly insidegpu.ViewProps.Childrenabove a 2D overlay canvas.
Switching between 2D and 3D scenes
Manager.View(opts) mounts a reactive view host that switches seamlessly between 2D canvas scenes (Controller.Scene / Controller.Draw) and 3D or native view scenes (Controller.View, such as gpu.View or Overlay3D.View) while every scene shares the same *input.Actions and the same *sound.Mixer:
mgr := scene.NewManager(cx)
actions.WatchKeys(cx) // keys reach Actions whether or not the stage holds focus
mgr.Actions = actions // set before mgr.View: attached to the persistent stage view, survives 2D <-> 3D switches
mixer := sound.NewMixer(cx, "game.sound") // on the Manager's scope, not a scene's, so music plays on across switches
mixer.Music("music").Play(theme, 0) // started once here, so no scene owns it
var overworld2D, dungeon3D *scene.Controller
overworld2D = &scene.Controller{
Scene: mapScene,
Update: func(dt time.Duration) {
if mgr.Actions.JustPressed("enter_3d") {
mgr.Switch(dungeon3D, scene.Fade(400*time.Millisecond, core.RGB(0x000000)))
}
},
}
dungeon3D = &scene.Controller{
View: func(scx *core.Scope) core.Node {
return ov.View(scx, gpu.ViewProps{
Style: core.Style{Width: core.Pct(100), Height: core.Pct(100)},
DepthFormat: gpu.FormatDepth24Plus,
OnReady: onReady,
OnFrame: onFrame,
})
},
Update: func(dt time.Duration) {
if mgr.Actions.JustPressed("exit_3d") {
mgr.Switch(overworld2D, scene.Fade(400*time.Millisecond, core.RGB(0x000000)))
}
},
}
mgr.Switch(overworld2D, nil)
return mgr.View(scene.HostOptions{
Alpha: func() float64 { _ = frameTick.Get(); return alpha },
Viewport: &viewport,
Children: persistentHUD,
})
- Stable GPU view mounting: each entered scene receives a unique instance ID rendered via
core.Each. Mounted 3Dgpu.Viewsurfaces and GPU pipelines stay alive across transition frames and acrossPush/Popof 2D overlays (transparent or opaque), and unmount cleanly when the scene exits. - View scope: the
cxpassed toController.Viewis the mounted row's scope, not the scopeEnterreceives. When a scene leaves,Exitruns andEnter's scope is disposed first, then the row and everything created underView'scxare unmounted in the sameSwitch,Pop, or transition step, so no frame orOnFramecallback runs in between. Create the state a 3D view reads every frame inViewor on the Manager's scope. - Transitions across 2D ↔ 3D:
Fade(d, color)fades the outgoing 2D or 3D scene tocoloron a top overlay canvas over the first half, reveals the incoming scene at the midpoint (0.5), and fades out over the second half;Crossfade(d)animates outgoing/incoming wrapperOpacity;Wipe(d, dir)uses exact path clipping between 2D scenes and smooth crossfade opacity when aController.Viewscene is involved;CustomTransition, or a built-in transition whoseDrawyou replaced, draws its own frames between 2D scenes and custom overlay effects above the active view otherwise. ATransitionwith a nilDrawshows the incoming scene for its wholeDuration, asManager.Drawdoes. - Shared input:
Manager.ViewattachesManager.Actionsto its persistent stage view whenViewis called, so setActionsfirst. Key events reach the stage only while it holds focus: passHostOptions.Refand call itsFocus()once mounted (focus and pointer lock then survive every switch), or callActions.WatchKeysas above.Switch,Push, andPopcallActions.Reset()by default so transient press edges and held keys do not leak into the next scene while all bindings, axes, and pointer lock stay intact (setManager.KeepInputOnSwitch = trueto preserve held inputs across transitions). - Shared sound: the Manager needs no mixer of its own. A
sound.Mixercreated on the Manager's scope (or an ancestor of it) is not disposed when scenes exit, so background music plays on and SFX groups stay live across every 2D ↔ 3D switch while each scene reaches the mixer through its own closures. A mixer created under a scene'sEnterscope stops with that scene. - 2D overlays & invalidation: pushing a
Transparent: true2D controller over a 3D scene keeps the 3D view visible underneath while pausing itsUpdateand settingPointerEventsNoneon the paused layer. WhenHostOptions.Viewportis set, transparent pushed 2D overlays treat a zeroBarColorascore.Transparentso margins do not obscure the 3D scene. Callmgr.Invalidate()to redraw mounted 2D canvases on demand without remounting 3D views.
For a complete runnable game that switches between a 2D courtyard overworld (scene.Scene + sprite.Batch) and a 3D glTF shrine (gpu.View), pushes a transparent 2D pause overlay over the 3D view, and shares one *input.Actions and *sound.Mixer across transitions, see examples/lantern3d.
Physics in scene files
Scenes authored in YAML with game/sceneformat can declare 2D (body2d, collider2d, trigger2d) and 3D (body3d, collider3d, trigger3d) physics components directly on objects, using named collision layers from game.yaml. Pass a built scene to sceneformat.BuildPhysics to instantiate its physics.World, physics.RigidWorld, and physics3d.World and step them each fixed tick alongside your scene.
2D lighting in scene files
YAML scenes can also set ambientColor and attach built-in light2d and occluder2d components (rect, polygon, or tilemap collision). sceneformat.Build constructs BuiltScene.Lights2D (*lights2d.Scene) automatically so BuiltScene.Draw renders the same 2D lights and shadows in the game and in the editor's lighting preview (game/editor).
2D navigation regions in scene files
YAML scenes can declare walkable and obstacle navregion2d polygons directly on objects, optionally subtracting solid tilemap collision geometry (subtractTileCollision: true). sceneformat.Build bakes them via game/navbake into BuiltScene.NavBake2D (*navbake.Mesh) and BuiltScene.NavMesh2D (*ai.NavMesh), so the editor's 2D NavMesh overlay and Test Path tool produce the exact same path as the game (game/editor).