Scene2D
A 2D world for a game: the nodes it draws (sprites, text, paths, tilemaps, 2D physics) plus an
orthographic Camera2D; open() shows it, one scene at a time. Not to be confused
with Scene, the 3D world; app screens are UIScreen.
- start a 2D game: create a scene and show it
- set the background color, or crisp pixel-art vs smooth texture filtering
- draw characters behind trees in a top-down game (y-sort)
- draw one sprite in front of another, or a whole group over the world
- group sprites and show or hide them together
- react to taps and drags anywhere in the 2D world
- find the sprite under a tap
- show the score or a pause button over the 2D game
- show a live minimap or a second 2D view inside the UI
- add scene-wide game logic (systems)
Platforms: iOS, Android, desktop, the web (Web Lite), the web player, the le.codes viewer app;
not in a 3d / core engine variant of an app built with lecodes app, where new Scene2D()
throws — check Scene2D.supported. Headless tests run a scene but never draw it.
At a glance
async function main() {
const scene = new Scene2D({ background: '#10131a', ySort: true }) // top-down: lower on screen draws in front
const tex = await Texture2D.load(asset('./hero.png'))
const hero = new Sprite({ texture: tex, anchor: [0.5, 1] }) // feet anchor: Y-sort by where it stands
scene.add(hero)
scene.addEventListener('click', ev => {
console.log('tapped', ev.target?.id ?? 'empty space', 'at world', ev.worldX, ev.worldY)
})
scene.open()
}
main()Loading happens inside an async function — see no top-level await.
Create a scene: background color and texture filter
new Scene2D(options?: {
background?: ColorInput // clear color
filter?: 'nearest' | 'linear' // default texture sampling; default nearest (crisp pixel art)
ySort?: boolean // top-down depth, see draw order below; default false
})
scene.background = '#10131a' // settable later too
scene.ySort = true // settable later too
scene.camera // the scene's Camera2D (readonly)filter is the renderer's default sampling — a global setting, not per scene. It
is (re)applied on open(), so the currently-open scene's choice wins; a node's own material
(Material2D) filter overrides it for that node. Use 'linear' for hi-res / non-pixel-art
assets; omit to leave the current setting.
Show the scene and close it: open / close
scene.open(options?: { transition? }): this // become the visible destination; replaces a screen / another scene
scene.close(options?: { transition? }): this // stop showing it
scene.destroy(): void // detach its systems, close, free the native scene
Scene2D.active // static: the currently open Scene2D, or null
scene.onOpen(cb: () => void): this // became the visible destination (a pop back to it too)
scene.onClose(cb: () => void): this // stopped being visible (closed, replaced, covered)
scene.onBack(cb: () => void): this // system back while the scene is currenttransition defaults to 'none'. The scene itself never moves: the screen it replaces, or that
comes over it, plays the transition — see transitions.
the 2D engine — physics, sprite animation — advances only while a scene is open or
shown in a UIImage. Until then bodies hang where they were created.
on Android the 2D engine starts with the first texture upload (Texture2D.load, a
canvas texture): until then a scene draws nothing, not even its background, and does not step.
destroy() frees the scene, not its nodes: destroy() the nodes you are done with.
Add sprites and nodes to the scene: add / remove
scene.add(...nodes: Node2D[]): this // draw these nodes, each with its whole subtree
scene.remove(...nodes: Node2D[]): this // stop drawing them and their subtreesA scene draws subtrees: scene.add(cart) draws the cart and every node under it, so add the
roots only. A node parented later under a node of the scene
(node.add(child) / setParent) joins that scene; parented under a node
in no scene, it leaves it. scene.remove(cart) takes the cart and its children out together. A
child detached from its parent (cart.remove(wheel), setParent(null)) stays in the scene as a
root of its own. .scene2d.ts files add every node for you.
visible is inherited the same way: a hidden node hides its whole subtree.
const scene = new Scene2D({ background: '#10131a' })
const cart = new Node2D()
cart.add(
new Sprite({ size: [60, 20], color: '#c84', position: [0, 10] }), // the body
new Sprite({ size: [12, 12], color: '#333', position: [-20, 0] }), // the wheels
new Sprite({ size: [12, 12], color: '#333', position: [20, 0] }),
)
scene.add(cart) // the cart and its three children draw
scene.open()
cart.x = 100 // all three move with it
cart.visible = false // and hide with itA node in a scene (or under a parent) is held by the engine: dropping your reference does not free
it. remove() hands a root back to its JS handle; node.destroy() frees it.
Characters behind trees in a top-down game: draw order, renderPriority, z, ySort
In a top-down game a character walks behind a tree and then in front of it: turn on the scene's
ySort and give characters and trees a feet anchor. renderPriority and z put one sprite, or a
whole band of them, in front of or behind the others.
node.renderPriority = 6 // coarse order: 0 drawn first … 7 last; default 4
node.z = 1 // within one renderPriority, higher on top; default 0
scene.ySort = true // within one renderPriority and z, lower on screen on topWhat draws over what is decided by these keys, in this order:
renderPriority— eight buckets, 0 first and 7 last, 4 the default (the 3DMesh.renderPriority); rounded and clamped to 0..7. A backdrop at 0, a world-space overlay at 6.z— within one priority, any number.- the node's pass — a text's halo and a stroke's outline draw under every body of that priority and z, a filled path's border over them (see Text2D, Path2D).
- with
ySorton, world Y — the node lower on screen (smaller Y) draws in front: the classic "characters walk behind trees" look of a top-down game.
Nodes equal in all of these draw in the renderer's order (it groups them by texture to batch them):
give overlapping nodes different z. Y-sort is the last key, not a mode — z still splits a
Y-sorted scene into bands: a ground tilemap at z: -1 stays under every character at z: 0, a
bird at z: 1 flies over them.
async function main() {
const scene = new Scene2D({ background: '#3b4a2a', ySort: true })
const props = await Texture2D.load(asset('./props.png'))
const grass = new Sprite({ size: [640, 480], color: '#4a6b3a' })
grass.z = -1 // under everything at z 0
const tree = new Sprite({ texture: props, anchor: [0.5, 1], position: [0, 40] })
const hero = new Sprite({ size: [16, 24], color: '#4f7cff', anchor: [0.5, 1], position: [0, 20] }) // lower: in front
const banner = new Sprite({ size: [200, 32], color: '#a33', position: [0, 160], renderPriority: 6 }) // over the world
scene.add(grass, tree, hero, banner)
scene.open()
hero.animateTo({ y: 60, duration: 1000 }) // walks up past the tree's feet: now behind it
}
main()Y-sort compares node positions, i.e. anchor points. Give characters and props in a
Y-sorted scene a bottom-center anchor (anchor: [0.5, 1] — the "feet") so depth sorts where
they touch the ground.
Find the sprite at a point: pick
scene.pick(worldPoint: Vec2Like): Node2D | nullTopmost visible sprite of this scene whose world bounds (the axis-aligned box around its quad)
contain the point — the one drawn on top, by the draw order; a node hidden by itself
or by a parent is skipped, and a text, a path or a tilemap is never picked. A body-free hit-test, no
physics needed. Pair with scene.camera.screenToWorld() to convert a tap position.
For automatic pointer dispatch to nodes, give the node a physics body instead — see picking in 2D physics.
Taps and drags anywhere in the scene: click / touchstart
scene.addEventListener('click', (ev: ClickEvent) => void) // pointer-up anywhere in the scene
scene.addEventListener('touchstart', (ev: TouchStartEvent) => void) // pointer-down; ev.track() for drags
scene.removeEventListener(channel, callback)Only the active scene (Scene2D.active) receives pointer events, and only the pointers the UI
over it does not claim (the HUD rule). ev.target is the node whose body is under the
pointer — the topmost Physics2D, Trigger2D or character by draw order — or null for empty
space; ev.worldX / ev.worldY give the point in world space. The hit node's own listener runs
first. Every click then reaches the scene listeners; a touchstart reaches them only while
nobody has called ev.track({...}) yet — the node, or the first scene listener, that tracks takes
the gesture. See pointer events & gestures.
in headless tests the 2D view is never sized, so worldX / worldY of a scripted tap
are wrong and it hits the wrong node.
Scene-wide game logic: scene.system
scene.system(Class, opts?): scene & { name: instance } // build a System<'name', Scene2D> from opts
scene.get(Class) · scene.has(Class) · scene.removeSystem(Class)Scene-wide logic (input, spawners, the HUD) — see systems. destroy()
detaches them first.
A HUD over the scene: scene.widgets
The score, a health bar or a pause button over a 2D game are the scene's
widgets: laid out over it while it is shown, and they do not move with the
camera (text that does is a Text2D).
A pointer the UI claims never reaches the scene. The UI claims a pointer that goes down on an
interactive node — a UIButton, a UIWidget or UIScreen with onTouchStart — on a scrollable
whose content overflows, on a text input, on the keyboard, or on a widget's scrim
(overlayColor). Every other pointer is the scene's, with all its moves and its release: one
beside the widgets, and one on a part of a widget that is not interactive — its plain text, an
image, its background. A drag that starts on a button stays the button's when it leaves it; one
that starts on the scene stays the scene's when it crosses a widget. The same rule as a 3D scene's
widgets, on every host.
const score = signal(0)
const scene = new Scene2D({ background: '#10131a' })
scene.addEventListener('click', () => { score.value++ }) // every tap the UI does not claim
const hud = UIWidget(
UIText(() => `Score: ${score.value}`).style({ color: 'white', fontSize: 20 }), // plain text: a tap on it scores
UIButton(UIText('Reset').style({ color: 'white' })).onClick(() => { score.value = 0 }), // a button: its taps are its own
).style({ top: 'safe-top', left: 16, gap: 12 })
scene.widgets(hud)
scene.open()A live 2D view inside the UI (minimap): UIImage(scene)
const minimap = UIImage(scene).style({ width: 160, height: 120 })A UIImage whose source is a scene draws it live into its box every frame, through the scene's
own camera — a minimap, a portrait. The scene needs no open() and keeps simulating; the image
has no intrinsic size, so give it a width and a height. Drawn on iOS, Android and desktop; the web
player and headless tests leave the box empty.
See also
- Node2D — transform, hierarchy,
renderPriority/z, events - Camera2D — zoom, screen↔world conversion
- Sprite — textured nodes, anchors
- Text2D — text in the world: labels, nameplates
- Path2D — lines, polygons and curves
- 2D physics — what makes a node pointer-hittable
- Pointer events & gestures —
ClickEvent,ev.track()