create-dreamer-app 1.0.13 → 1.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/template/DISCO_DREAMER_REFERENCE.md +102 -19
- package/template/package.json +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Disco Dreamer reference
|
|
2
2
|
|
|
3
|
-
A practical guide to building browser games with `discodreamer`. Examples use the public API in version 1.0
|
|
3
|
+
A practical guide to building browser games with `discodreamer`. Examples use the public API in version 1.2.0 and TypeScript with JSX.
|
|
4
4
|
|
|
5
5
|
## How a game runs
|
|
6
6
|
|
|
@@ -8,7 +8,7 @@ Disco Dreamer draws a tree of game objects onto a 2D canvas. Components are func
|
|
|
8
8
|
|
|
9
9
|
Your root function runs again on every animation frame. Each frame, the engine builds the tree, solves collisions, manages sound, draws the tree, and cleans up. A state setter updates stored data immediately; it does not schedule a separate render.
|
|
10
10
|
|
|
11
|
-
- Coordinates use CSS pixels,
|
|
11
|
+
- Coordinates use CSS pixels by default, or scaled game units when configured through `registerRoot`. In both modes, `(0, 0)` is at the canvas's top-left, positive `x` points right, and positive `y` points downward.
|
|
12
12
|
- Child positions are relative to their parent `Scene` or `RigidBody2D`.
|
|
13
13
|
- Siblings draw in ascending `z` order; higher values appear later, on top. This is local to each parent, not a global depth order.
|
|
14
14
|
- Update times and interpolation durations are in milliseconds. Convert `dt` to seconds for movement expressed in units per second.
|
|
@@ -71,6 +71,33 @@ Use `.tsx` files for JSX. Arrays and conditional children are supported, such as
|
|
|
71
71
|
|
|
72
72
|
The examples below are independent excerpts; add their named imports from `discodreamer` to your game file. Asset paths such as `/player.png` are examples: supply files at URLs your app serves.
|
|
73
73
|
|
|
74
|
+
### `registerRoot(Root, config?)`
|
|
75
|
+
|
|
76
|
+
Registers the single root function and starts the game loop. Omitting `config` uses `{ units: "pixels", scaling: 0.01 }`, so existing games use CSS-pixel coordinates. To enable scaled game units:
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
registerRoot(Game, { units: "scale", scaling: 0.01 });
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
When supplying a config, include both fields:
|
|
83
|
+
|
|
84
|
+
| Field | Values | Behavior |
|
|
85
|
+
| --- | --- | --- |
|
|
86
|
+
| `units` | `"pixels"` or `"scale"` | Selects CSS pixels or scaled game units |
|
|
87
|
+
| `scaling` | Finite number greater than `0` | Fraction of the canvas's shorter CSS dimension occupied by one game unit in scale mode; validated in both modes |
|
|
88
|
+
|
|
89
|
+
In scale mode, the engine recalculates the CSS-pixel size of one game unit before building the tree each frame:
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
unit = Math.min(canvas.clientWidth, canvas.clientHeight) * scaling;
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
With `scaling: 0.01`, one game unit occupies 1% of the shorter canvas dimension, so that dimension fits 100 game units. An `800 × 600` CSS-pixel canvas has `unit = 6` and a game viewport of approximately `133.33 × 100`; a rectangle with `width={10}` draws 60 CSS pixels wide. With `scaling: 0.02`, the shorter dimension fits 50 game units.
|
|
96
|
+
|
|
97
|
+
Positions, display widths and heights, circle radii, and font sizes use the selected coordinate units. Resizing changes the size of a scaled unit while stored positions and sizes retain their numeric values. Source image dimensions and sprite-sheet frame sizes remain source pixels; specify sprite display dimensions explicitly when needed for your chosen scale.
|
|
98
|
+
|
|
99
|
+
Viewport dimensions and pointer coordinates use the same units as drawing. Device pixel ratio is handled internally for canvas resolution; no DPR conversion is needed in game code. In pixel mode, `unit` is `1` and `scaling` does not affect rendering. If the calculated unit is zero or non-finite, the engine falls back to `1` for that frame.
|
|
100
|
+
|
|
74
101
|
## State and keys
|
|
75
102
|
|
|
76
103
|
### `gameState(key, initialValue)`
|
|
@@ -86,6 +113,19 @@ setScore((previous) => previous + 1);
|
|
|
86
113
|
|
|
87
114
|
`initialValue` initializes a new state slot; changing it on later frames does not reset existing state. Setters accept either a replacement or a function of the previous value. Replace objects rather than mutating them.
|
|
88
115
|
|
|
116
|
+
For lazy initialization, pass a synchronous function returning the initial value (`T | (() => T)`). It runs only when the resolved state slot is created:
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
const [position, setPosition, getPosition] = gameState("player.position", () => {
|
|
120
|
+
const { width, height } = gameViewport();
|
|
121
|
+
return { x: width / 2, y: height / 2 };
|
|
122
|
+
});
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Pass `() => buildValue()` to defer work until initialization. Passing `buildValue()` instead evaluates it on every hook call, even when the state already exists. A viewport-based initializer sets the starting position; it does not reposition existing state after resizing. If cleanup removes the slot and it is later recreated, its initializer runs again. For shared `$` keys, only the call creating the slot runs its initializer.
|
|
126
|
+
|
|
127
|
+
Function arguments are treated as initializers, and function arguments to the setter are treated as updaters. To store a callback as data, wrap it in an object, for example `gameState("action", { run: () => console.log("Go") })`.
|
|
128
|
+
|
|
89
129
|
Keys identify persistent data across frames. Give each stateful hook and each body instance a stable, descriptive key. For repeated entities, include an entity ID, such as `` `enemy.${id}.health` ``.
|
|
90
130
|
|
|
91
131
|
Internally, ordinary keys receive numbered slots for consecutive stateful calls using the same key. Their order must stay consistent. Reusing a key after a different ordinary key starts its numbering again, which can alias an earlier slot. The simplest application pattern is to use a distinct key for each hook and avoid sharing keys with component internals. Keep stateful hook calls in a consistent order each frame.
|
|
@@ -149,7 +189,8 @@ Displays an image or a sprite-sheet animation. Supply exactly one of `src` or `a
|
|
|
149
189
|
| `animation` | Result of `gameAnimation` |
|
|
150
190
|
| `x`, `y`, `z` | Position and sibling draw order; default `0` |
|
|
151
191
|
| `width`, `height` | Display size; defaults to image dimensions or animation frame size |
|
|
152
|
-
| `rotation` | Degrees around the
|
|
192
|
+
| `rotation` | Degrees around the pivot point; default `0` |
|
|
193
|
+
| `pivot` | Normalized rotation point; default `{ x: 0.5, y: 0.5 }` (center) |
|
|
153
194
|
|
|
154
195
|
```tsx
|
|
155
196
|
<Sprite src="/player.png" x={100} y={80} width={64} height={64} />
|
|
@@ -157,6 +198,13 @@ Displays an image or a sprite-sheet animation. Supply exactly one of `src` or `a
|
|
|
157
198
|
|
|
158
199
|
The sprite's position is its unrotated top-left corner. Images are cached by URL, and a sprite draws nothing until its image is ready. Rotation affects drawing, not physics bounds.
|
|
159
200
|
|
|
201
|
+
Pivot coordinates are fractions of the displayed width and height: `{ x: 0, y: 0 }` is the top-left, and `{ x: 1, y: 1 }` is the bottom-right. The pivot applies to both static images and animation frames. Changing it changes the rotation point while preserving the image's unrotated top-left position. For example, rotate a sword near its handle:
|
|
202
|
+
|
|
203
|
+
```tsx
|
|
204
|
+
<Sprite src="/sword.png" x={100} y={80}
|
|
205
|
+
pivot={{ x: 0.5, y: 0.9 }} rotation={45} />
|
|
206
|
+
```
|
|
207
|
+
|
|
160
208
|
### `Text`
|
|
161
209
|
|
|
162
210
|
Draws left-aligned, top-aligned text in the supplied `color`, or white by default. Uses `sans-serif` unless a font family is supplied.
|
|
@@ -166,7 +214,7 @@ Draws left-aligned, top-aligned text in the supplied `color`, or white by defaul
|
|
|
166
214
|
| `value` | Required | Text string to draw |
|
|
167
215
|
| `x`, `y`, `z` | `0` | Position and sibling draw order |
|
|
168
216
|
| `color` | `"white"` | Text fill color as a canvas color string, such as `"red"` or `"#ff00ff"` |
|
|
169
|
-
| `fontSize` | `25` | Font size in
|
|
217
|
+
| `fontSize` | `25` | Font size in the selected coordinate units |
|
|
170
218
|
| `font` | `""` (renders as `sans-serif`) | Font family name, such as a name registered with `addCustomFont` |
|
|
171
219
|
| `width` | `Infinity` | Maximum canvas text draw width |
|
|
172
220
|
|
|
@@ -258,14 +306,22 @@ A stateful moving body. Put drawing components and one or more `Bounds` inside i
|
|
|
258
306
|
| `forces` | `[]` | Force vectors in newtons, applied each frame |
|
|
259
307
|
| `drag` | `0` | Exponential velocity damping per second |
|
|
260
308
|
| `restitution` | `1` | Bounce factor; `0` removes bounce; a pair uses the lower factor |
|
|
261
|
-
| `
|
|
309
|
+
| `interactionMode` | `"body"` | Selects whether interaction settings belong to the body or its bounds |
|
|
310
|
+
| `layer` | Unset | Layer name used by other colliders' filters; body mode only |
|
|
262
311
|
| `collidesWith` | `[]` | Layers eligible for physical collision |
|
|
263
312
|
| `hitsWith` | `[]` | Layers to report overlap with, without requiring physical response |
|
|
264
313
|
| `ref` | Unset | Key returned by `gameRef` |
|
|
265
314
|
| `onChange` | Unset | Callback receiving `{ position, velocity }` |
|
|
266
315
|
| `children` | `[]` | Visuals and bounds attached to the body |
|
|
267
316
|
|
|
268
|
-
Physics treats one world unit as one centimeter. The renderer displays one unit as one CSS pixel.
|
|
317
|
+
Physics treats one world unit as one centimeter. The renderer displays one unit as one CSS pixel in pixel mode, or at the configured scale in scale mode. Scaling changes the visual size of the world without changing the numeric physics inputs or simulation units.
|
|
318
|
+
|
|
319
|
+
Choose one place for interaction settings per body:
|
|
320
|
+
|
|
321
|
+
- In `interactionMode="body"` (the default), set `layer`, `collidesWith`, and `hitsWith` on `RigidBody2D`. All its bounds use these settings. Supplying any of these settings on an owned bound, including an empty array, throws an error during physics collection.
|
|
322
|
+
- In `interactionMode="bounds"`, set those properties on individual `Bounds`. Body-level interaction settings are forbidden by the prop types. Each bound uses its own settings, with no fallback to the body.
|
|
323
|
+
|
|
324
|
+
The mode selects interaction settings only. Bounds still belong to the body; movement, mass, restitution, and contact-hook identity remain at body level.
|
|
269
325
|
|
|
270
326
|
Keep `x`, `y`, `velocity`, and `mass` props stable to let the simulation evolve. Changing any of these inputs resets the body's stored position, velocity, and mass to the currently supplied values. For movement that does not reset the body, use forces. `onChange` runs initially and on tracked changes; velocity comparisons use a threshold of `1` unit/s, while position changes also trigger it.
|
|
271
327
|
|
|
@@ -282,14 +338,26 @@ Defines collision geometry owned by its containing body. Choose either rectangle
|
|
|
282
338
|
|
|
283
339
|
Rectangle bounds use their top-left corner; circle bounds use their center. `position` is a local offset (default `{ x: 0, y: 0 }`). Optional `outline` displays the geometry for debugging; `style` controls its fill/stroke and `z` controls its visual sibling order. Bounds are invisible by default. Standalone bounds outside a body do not participate in physics.
|
|
284
340
|
|
|
341
|
+
In bounds mode, `layer`, `collidesWith`, and `hitsWith` are optional. An omitted layer is unset; omitted interaction lists behave as `[]`. These settings replace body-level configuration entirely. For example, give a static body one solid bound and a separate sensor:
|
|
342
|
+
|
|
343
|
+
```tsx
|
|
344
|
+
<RigidBody2D key="platform" y={300} mass={0} interactionMode="bounds">
|
|
345
|
+
<Bounds width={200} height={20}
|
|
346
|
+
layer="ground" collidesWith={["player"]} />
|
|
347
|
+
<Bounds width={200} height={40} position={{ x: 0, y: -40 }}
|
|
348
|
+
layer="sensor" hitsWith={["player"]} />
|
|
349
|
+
</RigidBody2D>
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
A player with `layer="player"` and `collidesWith={["ground"]}` can physically collide with the ground. The sensor reports hits through `gameHit("platform", ...)` without causing physical response.
|
|
353
|
+
|
|
285
354
|
### `gameCollision(key, handler)` and `gameHit(key, handler)`
|
|
286
355
|
|
|
287
|
-
Call these each frame with the body's public `key`.
|
|
356
|
+
Call these each frame with the body's public `key`. Each handler receives `(otherKey: string, otherLayer: string, ownLayer: string | undefined)`. `otherKey` is the other body's public key; `otherLayer` and `ownLayer` are the effective layers of the two contacting bounds, selected according to each body's interaction mode. Existing callbacks accepting only two arguments remain valid.
|
|
288
357
|
|
|
289
|
-
-
|
|
290
|
-
-
|
|
291
|
-
-
|
|
292
|
-
- Hits are directional: only the observing body's `hitsWith` needs to include the other body's layer. The observing body does not need its own layer.
|
|
358
|
+
- Physical collisions require both contacting bounds' effective `collidesWith` lists to include the other's effective layer. Both layers are defined for a physical collision.
|
|
359
|
+
- Hits are directional: only the observing bound's effective `hitsWith` needs to include the other bound's effective layer. `otherLayer` is always defined; `ownLayer` can be `undefined` for a hit.
|
|
360
|
+
- For each observing body key, events are grouped by the other body's public key and both effective layers. Multiple contacts with the same combination produce one callback per frame; distinct layer pairs produce separate callbacks, even when the other body is the same.
|
|
293
361
|
- Hits alone do not separate bodies or change their velocities.
|
|
294
362
|
- Hooks read the previous frame's contact results because the current collision pass happens after tree construction. Contacts are reported repeatedly while detected; these are not enter/exit events.
|
|
295
363
|
|
|
@@ -299,8 +367,10 @@ function PhysicsExample() {
|
|
|
299
367
|
if (otherLayer === "world") console.log("Ball contacted world body:", otherKey);
|
|
300
368
|
});
|
|
301
369
|
|
|
302
|
-
gameHit("ball", (otherKey, otherLayer) => {
|
|
303
|
-
if (otherLayer === "world")
|
|
370
|
+
gameHit("ball", (otherKey, otherLayer, ownLayer) => {
|
|
371
|
+
if (otherLayer === "world") {
|
|
372
|
+
console.log("Ball overlapped world body:", otherKey, "using layer:", ownLayer);
|
|
373
|
+
}
|
|
304
374
|
});
|
|
305
375
|
|
|
306
376
|
return (
|
|
@@ -368,7 +438,7 @@ The snapshot's data fields remain the values captured when `snapshot()` was call
|
|
|
368
438
|
|
|
369
439
|
### `gameUpdate(handler)`
|
|
370
440
|
|
|
371
|
-
Calls `handler(dt, frame, viewport)` immediately whenever the hook is evaluated. Used once in a component that runs every frame, it runs once per frame. `frame` starts at `0`; `dt` starts at `0` and then reflects the interval measured at the previous cleanup. `viewport` contains `{ width, height }` in CSS pixels.
|
|
441
|
+
Calls `handler(dt, frame, viewport)` immediately whenever the hook is evaluated. Used once in a component that runs every frame, it runs once per frame. `frame` starts at `0`; `dt` starts at `0` and then reflects the interval measured at the previous cleanup. `viewport` contains `{ width, height }` in the selected coordinate units: CSS pixels by default, or game units in scale mode.
|
|
372
442
|
|
|
373
443
|
```ts
|
|
374
444
|
gameUpdate((dt, frame, viewport) => {
|
|
@@ -405,7 +475,7 @@ Reads current input; call it each frame. It invokes the listener immediately for
|
|
|
405
475
|
| `touchStart` | `{ x, y }` | Primary pointer press on the canvas |
|
|
406
476
|
| `touchEnd` | `{ x, y }` | Primary pointer release or cancellation |
|
|
407
477
|
|
|
408
|
-
Key names use `KeyboardEvent.key`, for example `"ArrowLeft"`, `"a"`, or `" "` for space. Despite the `touch` names, pointer input supports mouse, touch, and pen, tracking one active pointer. Positions are relative to the canvas content area in CSS
|
|
478
|
+
Key names use `KeyboardEvent.key`, for example `"ArrowLeft"`, `"a"`, or `" "` for space. Despite the `touch` names, pointer input supports mouse, touch, and pen, tracking one active pointer. Positions are relative to the canvas content area in the selected coordinate units. In scale mode, canvas-relative CSS-pixel positions are divided by the current unit size; DPR does not enter this conversion.
|
|
409
479
|
|
|
410
480
|
```ts
|
|
411
481
|
gameEvent("keyDown", ({ key }) => {
|
|
@@ -418,7 +488,7 @@ gameEvent("touchStart", ({ x, y }) => {
|
|
|
418
488
|
|
|
419
489
|
### `gameViewport()`
|
|
420
490
|
|
|
421
|
-
Returns the canvas's current
|
|
491
|
+
Returns the canvas's current size as `{ width, height }` in the selected coordinate units. In pixel mode these are CSS dimensions; in scale mode they are CSS dimensions divided by the current unit size. With `scaling: 0.01` and a nonzero canvas size, the shorter dimension is 100 game units. Use this for responsive placement; the engine handles the canvas backing resolution for device pixel ratio.
|
|
422
492
|
|
|
423
493
|
```ts
|
|
424
494
|
const { width, height } = gameViewport();
|
|
@@ -484,7 +554,7 @@ The ID retains the resolved value's type for `gameAsyncThen`; widening it to pla
|
|
|
484
554
|
|
|
485
555
|
Timers use wall-clock milliseconds and invoke handlers synchronously when `when` is called. They do not schedule browser timer callbacks. Call the hook and its returned `when` function each frame, and call `start` only when you want to start or restart the timer. Keep each hook's key stable to preserve its state across frames. Timer state is removed by the normal state cleanup when the hook is no longer used.
|
|
486
556
|
|
|
487
|
-
### `
|
|
557
|
+
### `gameTimeout(key)`
|
|
488
558
|
|
|
489
559
|
Returns the readonly tuple `[start, when, clear, timeRemaining]`.
|
|
490
560
|
|
|
@@ -501,7 +571,7 @@ The timeout starts inactive. By default, `when` clears it before calling the han
|
|
|
501
571
|
|
|
502
572
|
```ts
|
|
503
573
|
const [startTimeout, whenTimeout, clearTimeout, timeRemaining] =
|
|
504
|
-
|
|
574
|
+
gameTimeout("notice.timeout");
|
|
505
575
|
|
|
506
576
|
gameEvent("keyDown", ({ key }) => {
|
|
507
577
|
if (key === "n") startTimeout(2000);
|
|
@@ -550,7 +620,7 @@ Use an ordinary key for `gameInterval`, not a `$` literal key: the interval stor
|
|
|
550
620
|
|
|
551
621
|
Creates an animation descriptor for `Sprite`. `animations` is an ordered array of `[condition, frames, options?]`; the first true condition wins. A condition can be a boolean or a function returning a boolean. Frame numbers are zero-based, counted left to right and then top to bottom across the sheet.
|
|
552
622
|
|
|
553
|
-
Config requires `src` and `size
|
|
623
|
+
Config requires `src` and `size`, which describes each frame in source pixels. Use a number for square frames (`size: 32`) or an object for rectangular frames (`size: { width: 32, height: 48 }`). Frames must form a regular grid with no spacing or margins; width determines the number of columns, and height determines row offsets. Optional `fps` defaults to `24`; `loop` defaults to `true`. A frame group's `{ loop }` overrides that default. Switching the selected group restarts its timing.
|
|
554
624
|
|
|
555
625
|
Each frame group's optional third item also accepts `fps`, for example `{ fps: 12 }` or `{ fps: 12, loop: false }`. A group's `fps` overrides the config's `fps`; when omitted, the group inherits the config rate (or the default of `24`). Use a positive FPS for normal playback. The group's rate controls both frame progression and completion timing.
|
|
556
626
|
|
|
@@ -567,6 +637,19 @@ function AnimatedPlayer({ moving }: { moving: boolean }) {
|
|
|
567
637
|
|
|
568
638
|
The moving group plays at 12 FPS; the fallback group inherits 8 FPS from config. Switching groups restarts playback at the newly selected group's rate.
|
|
569
639
|
|
|
640
|
+
For rectangular frames, configure the source dimensions independently from the display size:
|
|
641
|
+
|
|
642
|
+
```tsx
|
|
643
|
+
const animation = gameAnimation("character.animation", [
|
|
644
|
+
[true, [0, 1, 2, 3]],
|
|
645
|
+
], { src: "/character-sheet.png", size: { width: 32, height: 48 } });
|
|
646
|
+
|
|
647
|
+
// Display each 32 × 48 source frame at twice its size:
|
|
648
|
+
return <Sprite animation={animation} width={64} height={96} />;
|
|
649
|
+
```
|
|
650
|
+
|
|
651
|
+
If `Sprite` display dimensions are omitted, they default to the source frame dimensions. Numeric `size` values continue to work unchanged.
|
|
652
|
+
|
|
570
653
|
Use a final `true` condition as a fallback. A non-looping group holds its final frame. Call `animation.onAnimationFinish(handler)` each frame to handle its completion transition; it is not a persistent listener. Keep the source URL unchanged for an animation key, and use a positive frame size that fits the sheet.
|
|
571
654
|
|
|
572
655
|
### `gameImage(src)`
|