Writing a Cart
The entry point, the frame loop, and the manifest
A cart is one React tree and one frame loop. Everything else on this page is detail.
If you have never written React, that is the thing to learn first. Components, JSX and hooks are assumed everywhere here, and react.dev/learn is the place to start. None of it is Unity specific, so any React you know already applies.
import { useRef } from "react"
import { View, Text, mount, useFrame, input, type VisualElement } from "oj"
function Game() {
const x = useRef(100)
const ref = useRef<VisualElement>(null)
useFrame((dt) => {
x.current += input.keyboard.wasd().x * 300 * dt
if (ref.current) ref.current.style.left = x.current
})
return (
<View style={{ flexGrow: 1, backgroundColor: "#14181d" }}>
<View ref={ref} style={{ position: "absolute", top: 100, width: 40, height: 40, backgroundColor: "#ffd166" }} />
<Text style={{ color: "white" }}>Move with A and D</Text>
</View>
)
}
mount(<Game />)What you draw with, and how styling and events work, is Elements and Styling.
mount()
mount(<Game />) is the entry point. The container already knows the root and the stage, so a cart plumbs neither through its tree.
mount(<Game />)
mount(<Game />, { theme: false }) // skip the built-in control thememount() also styles the controls the runtime provides (Button, Slider, TextField and friends), because UI Toolkit's own runtime theme is built for the editor and looks out of place next to a cart. It touches only those controls, an inline style beats it, and { theme: false } turns it off. It comes with you into Unity, since mount() applies it rather than the site.
useFrame()
useFrame((dt) => {
// dt is seconds since the last frame
})The callback runs every frame for as long as the component is mounted. dt is what makes a cart run at the same speed on a 60 Hz laptop and a 144 Hz monitor, so multiply movement by it rather than assuming a fixed step.
The runtime holds dt to at most a tenth of a second, so the first frame back from a stall or a backgrounded tab moves things by one tenth rather than by however many seconds passed. Clamp it lower if a tenth is still too much for your simulation:
useFrame((dt) => {
const step = Math.min(dt, 1 / 20)
// ...
})The second argument is the time that really passed, never held:
useFrame((dt, realDt) => {
elapsed.current += realDt // a stopwatch on screen keeps to the clock on the wall
})Move things by dt and count real time with realDt. After a two second stall, dt is 0.1 and realDt is 2.
Keep per-frame work out of React. Setting state sixty times a second re-renders the tree sixty times a second; writing to ref.current.style does not. Drive motion through refs in useFrame, and let React handle what changes a few times a second, like a score or a menu.
The callback can read state and props directly. Each frame runs the callback from your latest render, so a comparison against a state value sees the current one. The optional second argument, a dependency list, only decides when the frame subscription is remade, and you will rarely need it.
useLateFrame()
A frame runs in three parts: every useFrame, then the physics world steps, then every useLateFrame. A velocity or a walk set in useFrame moves its body in the same frame's step. A position read in useFrame is where the last step left it, which is a frame old by the time it is drawn.
So a camera that follows something, or a label placed over a body, goes in useLateFrame, which sees where everything is about to be drawn:
useLateFrame(() => {
const at = me.actor?.position
if (at) scene.camera({ position: [at[0], at[1] + 6, at[2] - 8], lookAt: at })
})It takes the same arguments as useFrame. useFollowCamera already runs there.
Timers run as a browser runs them. Timeouts and intervals due in the same frame run one at a time, so an await in one resumes before the next starts, and a frame spends at most 4 ms on them: the rest run next frame, in the order they were due. That is runtime 1.6's; on 1.5 every timer due in a frame ran before any of their awaits resumed, all in that frame. useFrame and requestAnimationFrame callbacks are not limited.
Input
Read the player through input, the same module a normal OneJS project uses.
if (input.keyboard.wasKeyPressed("Space")) jump()
const move = input.keyboard.wasd()
const p = input.mouse.position
for (const touch of input.touches) aimAt(touch.position)Two things are specific to Play:
- Positions arrive in window pixels, the same numbers as
useStage()and pointer events. In a normal OneJS projectinput.mouse.positionis in Unity screen coordinates. - Key names are Unity's:
"W","Space","LeftArrow","Escape". They name the physical key rather than the letter printed on it, so WASD stays the same three keys on an AZERTY keyboard. wasd()andarrows()give y as +1 for up, Unity's way round, while the stage counts y downward. Subtract it to move up the screen.
input.pointerType is "mouse", "touch" or "pen": what the last press came from, or before any press, the device's best guess ("touch" on a phone or a tablet). Read it to show a stick or a keyboard hint, and a laptop with a touchscreen gets the right one for however it is being played.
Read positions through input in a frame loop. The same code then sees the mouse and every touch, so you get touch for free. When a pointer event is the right tool, e.localX and e.localY are relative to the element the handler is on.
A swipe, by finger or mouse drag, is one hook:
import { useSwipe } from "oj"
useSwipe((direction) => push(direction)) // "left" | "right" | "up" | "down"It fires once per gesture, after the pointer has travelled 28 pixels ({ threshold } changes that), and reads the same input your frame loop does, so a mouse and a finger need no separate code.
Mouse look
input.mouse.lock() hides the pointer and holds it in place, and input.mouse.delta still says how far the mouse moved each frame, so the mouse turns the view however far it goes, as in a first person cart:
const look = useRef({ yaw: 0, pitch: 0 })
useFrame(() => {
if (input.mouse.wasLeftPressed && !input.mouse.locked) input.mouse.lock()
if (input.mouse.locked) {
look.current.yaw += input.mouse.delta.x * 0.15
look.current.pitch = Mathf.Clamp(look.current.pitch - input.mouse.delta.y * 0.15, -80, 80) // y is down the screen
}
})A browser locks the pointer only when the player has just pressed something, so call lock() from a click, a tap or a key. Called anywhere else, it waits and locks on the next press, which is what a Play button on a menu wants. Escape always lets go: that is the browser's rule, and input.mouse.locked turns false on a following frame. input.mouse.unlock() lets go from code. While the pointer is locked it is over nothing, so a button on screen cannot be clicked: let go with a key, as Escape does. A phone has no pointer to lock, so there lock() does nothing and locked stays false; give it a stick instead.
Thumb controls for phones
A cart a phone can play needs controls a thumb can reach. useStick and usePad give you two kinds, read in the same frame loop as the keyboard:
import { Stick, Pad, useStick, usePad, useStage, useFrame } from "oj"
function Controls() {
const { width, height } = useStage()
const move = useStick("left")
const aim = useStick("right")
const jump = usePad({ x: width - 70, y: height - 170, radius: 34 })
useFrame(() => {
walk(move.x, move.y) // -1 to 1, y down the screen like the stage
if (aim.active) face(aim.x, aim.y)
if (jump.pressed) leap() // true on the one frame it went down
})
return <>
<Stick stick={move} />
<Stick stick={aim} color="#ffd166" />
<Pad pad={jump} label="Jump" />
</>
}- A stick appears under the thumb. The first thumb to come down on its half of the stage takes it and keeps it until it lifts, wherever it wanders, and the stick's centre follows a thumb that runs past its edge.
useStick("left"),useStick("right"), or a function of(x, y)that says which touches are its own.{ radius }sets how far it travels, 56 pixels by default. - A pad stays where you put it.
downwhile a finger is on it,pressedandreleasedfor one frame each. A thumb that lands on a pad is the pad's, never the stick's whose half it is in. - Both read
input.touchesonly, so a mouse never moves one, and the objects are live: read them inuseFrame, and nothing re-renders as a thumb moves.<Stick>and<Pad>draw them in stage pixels; put them at the top of your tree.
Buttons over the play area
A press on a button is the button's. input.mouse.overUI and each touch's overUI say whether a press came down on something that answers it: an element with an onClick, a pointer handler or an onChange, or one inside such an element. A View the size of the stage with no handler of its own does not count.
useFrame(() => {
if (input.mouse.wasLeftPressed && !input.mouse.overUI) fire()
})useStick and usePad already leave a thumb that lands on a button alone.
A View with a press handler counts as something that answers it, so one that fills the stage to catch every press would make every press overUI, and a stick would never move. Give such a View passThrough: its presses belong to the play area, so overUI stays false over it, while a button inside it still counts.
<View passThrough style={{ flexGrow: 1 }} onPointerDown={(e) => aimAt(e.x, e.y)}>
<Button text="Pause" onClick={pause} />
</View>The cameras' bind already carries it.
Sharing a link
share() opens the phone's share sheet, and copy() writes text to the clipboard:
import { Button, share, useRoom } from "oj"
const room = useRoom()
<Button text="Invite" onClick={async () => {
const said = await share({ url: room.inviteUrl, title: "Join me" }, { fallback: "copy" })
if (said === "copied") setNote("Link copied")
}} />- Call them from a press. A browser shares and copies only for a page the player has just pressed, so call them in an
onClick, or in the frame your loop reads a key, a click or a finger lifting. Anywhere else, a timer or a frame later, they answer"refused"without asking the browser, so what works on your desktop also works on a phone. share()answers"shared"once the player picked where,"cancelled"when they closed the sheet, and"refused"where there is no sheet or the browser said no. With{ fallback: "copy" }it copies the link instead (the text, with no link) and answers"copied". Most desktop browsers have no sheet, so the fallback is what an invite button wants.copy(text)answers"copied"or"refused".
Layout that follows the stage
useStage() gives you the window size to lay out against, and the responsive hooks read that same size: useBreakpoint(), useScreenSize(), useResponsive() and useMediaQuery(). mount() provides them; there is nothing to wrap.
The manifest
oj.json sits beside your source and describes the cart:
{
"name": "Sumo",
"author": "singtaa",
"description": "Everyone is a blob on a platform that keeps getting smaller.",
"entry": "index.tsx",
"tags": ["physics", "arcade"],
"controls": ["keyboard", "pointer", "touch"]
}| Field | |
|---|---|
entry |
The file to build from. Defaults to index.tsx, and has to name a file this cart ships |
name |
What the cart is called. Renaming changes its URL, and the old one redirects to the new |
description |
One or two sentences, shown on the cart's card and page |
tags, controls |
How the catalog files and filters it |
author |
Your handle. Not read by the site |
version |
This cart's version, like 1.2.0 |
exports |
The file other carts import from, when this cart is a piece for them |
dependencies |
The carts this one uses, each at an exact version. ojplay add writes it |
license |
The license for your code and your own files. MIT when you leave it out |
credits |
Files that are not yours to license, and what the cart's Stats say about them |
prompts |
true shows, on the cart's history page, the request each agent commit was made from. Off when you leave it out |
preload |
Files that load before the cart appears, like ["music/theme.ogg", "levels/1/"] |
Every one of those applies on every push, so editing the manifest is how you rename a cart or change how the catalog files it.
Versions
Changing version is how you release. The first push that builds with a new number makes that build the version, and the console says Released 1.3.0. A released version never changes: a later push under the same number still runs, and the console tells you once that the version stays as it was. Nothing releases until you press Push, so a number typed early waits for the rest of the change.
The site also tags that commit v1.3.0 in the cart's repository, so git tag lists the releases and git checkout v1.3.0 gets one. Those tags are the site's: a push cannot make, move or delete a tag named like a version. Any other tag you push is a label, shown beside its commit in the cart's History.
Using another cart
A cart can use another one's pieces, or run a whole one. From a terminal, with ojplay installed once (npm install -g ojplay):
ojplay add @singtaa/lightningThat adds it to dependencies at its newest version, fetches its source and art, and prints how to import it: import { Bolt } from "@singtaa/lightning". A cart with no exports is a whole cart, and import "@singtaa/lightning" runs it. In an empty folder, ojplay add starts a new cart that uses it. ojplay update moves to newer versions, and ojplay remove takes one out. In the editor, the carts a cart uses are listed under its files, read only.
Files that are not yours
A license covers only what you own. Mark each file that belongs to somebody else under credits, and the cart's Stats, in its editor, list it beside the license. A key ending in / covers a folder:
{
"credits": {
"portraits/": "game art © Blizzard Entertainment"
}
}A field you leave out is left alone, not reset. A manifest that never mentions tags does not clear them; it says nothing about them. That is what makes a short manifest safe.
An older manifest may still carry a stage. It publishes as before, with a note that the field is not read: every cart gets the whole window.
An older cart may carry schema or runtime. Nothing reads either: publishing puts your cart on the current container and records which one, so a cart you leave alone keeps working.
What else oj gives you
Beyond the components you already know:
Mathf, Vector2, Color |
Unity shaped, implemented in plain JavaScript. No interop cost |
random |
random.int(0, 10) straight away, or random("daily") for a seeded generator: daily challenges, replays and reproducible bugs. noise() on either, below |
drawing, useDrawing, Painter, Transform2D |
Vector drawing, with a transform stack; useDrawing(ref, draw, "frame") redraws every frame |
useWorld2D, useWorld |
Physics, 2D and 3D, stepped for you |
useScene, useModel, useOrbit, useFollowCamera |
A 3D world behind the UI, and cameras the player drags |
audio |
Sound over Unity's audio, not WebAudio, so it works in Unity too |
Code |
Syntax highlighted source, for a cart that shows its own |
useParticles, fx, sl |
Effects |
useTexture, assetUrl, preload, unload |
Your own files |
A world is made once, on mount, and a re-render does not rebuild it. Change a running world through its methods.
Noise
rng.noise() is smooth noise: nearby points give nearby values, from -1 to 1, the same for one seed on every machine. It is what terrain, clouds and a gentle wobble are made from.
const height = random("island 1").noise({ layers: 4 })
const y = 20 * height(x / 50, z / 50) // hills about 50 units across
const cloud = height(x / 50, z / 50, seconds * 0.1) // a third number moves through itIts bumps are about 1 apart, so divide by the size you want. layers adds finer detail on top, each layer at twice the detail and half the height, from 1 (smooth, the default) to 16. It draws nothing from the generator, so int and range give what they would have without it, and every noise() of one generator is the same field: rng.fork("caves").noise() is another.
Naming C# directly
oj wraps what most carts need, but the long tail of Unity and the BCL is not reachable any other way, so a cart can name C# itself:
const v = new CS.UnityEngine.Vector3(0, 1, 0)What you can reach is the set of namespaces the container preserves. A published cart plays the newest runtime of the line it was built on, which never changes what a cart can name, and that set only ever grows, so a cart that names something today keeps working. Something outside the set is not there at all, rather than being there and failing later.
Prefer oj's own Vector2, Color and Mathf where they cover what you need: they are plain JavaScript, so they cost nothing to cross.
Completions for CS come from a type package the editor fetches, so they can be missing when the cart itself runs perfectly well.
Things that behave differently from plain JavaScript
These follow Unity rather than the language, which is the point, but they surprise people:
Mathf.Sign(0)is1, not0, andMathf.Roundis banker's rounding, soMathf.Round(0.5)is0andMathf.Round(2.5)is2.Math.rounddiffers on both counts.Vector2is a class, not a struct.a = baliases where C# would have copied, so mutating one mutates the other. Useclone().- Positive y is down. The stage is a screen space with its origin at the top left, so a key press that should move something up subtracts.
randomranges are max exclusive for both integers and floats.UnityEngine.Randomis exclusive for integers and inclusive for floats.
Testing
Cart rules are ordinary functions and can be tested without a screen. Keeping them in their own file, with the drawing separate, means the rules get unit tests and the drawing needs none. It is also what makes a cart readable to somebody who forks it.
The cart as a whole is tested from a local clone. npx ojplay test runs it in the site's own container in a headless Chrome, and fails on a console error, an asset the site would not serve, or a row of controls out of line. Give it a script, npx ojplay test play.mjs, and the script's default export receives the running cart to drive: click(x, y), press("Space"), type("crane"), until(predicate), read() for the text on screen, and shot(file). A thrown error fails the run.