create-dreamer-app 1.0.12 → 1.0.14
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 +175 -12
- 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.1.0 and TypeScript with JSX.
|
|
4
4
|
|
|
5
5
|
## How a game runs
|
|
6
6
|
|
|
@@ -100,7 +100,7 @@ setScore((previous) => previous + 1);
|
|
|
100
100
|
const [score] = gameState("$score", 0); // Reads the incremented score.
|
|
101
101
|
```
|
|
102
102
|
|
|
103
|
-
The first call initializes the shared slot; later calls do not reset it. Literal keys do not advance or reset ordinary-key numbering. The `$` rule is implemented in `gameState`, so helpers that call it internally also inherit it. Use ordinary keys for those helpers, especially `gameAnimation`, which
|
|
103
|
+
The first call initializes the shared slot; later calls do not reset it. Literal keys do not advance or reset ordinary-key numbering. The `$` rule is implemented in `gameState`, so helpers that call it internally also inherit it. Use ordinary keys for those helpers, especially `gameAnimation` and `gameInterval`, which each need multiple numbered slots for a single key. Hooks that resolve keys directly, such as `gameEffect`, retain normal numbering.
|
|
104
104
|
|
|
105
105
|
State that is no longer used is removed during frame cleanup. This also applies to `$` keys: sharing a slot does not make it permanent. If an entity disappears for a frame and returns later, expect its state to initialize again.
|
|
106
106
|
|
|
@@ -149,7 +149,8 @@ Displays an image or a sprite-sheet animation. Supply exactly one of `src` or `a
|
|
|
149
149
|
| `animation` | Result of `gameAnimation` |
|
|
150
150
|
| `x`, `y`, `z` | Position and sibling draw order; default `0` |
|
|
151
151
|
| `width`, `height` | Display size; defaults to image dimensions or animation frame size |
|
|
152
|
-
| `rotation` | Degrees around the
|
|
152
|
+
| `rotation` | Degrees around the pivot point; default `0` |
|
|
153
|
+
| `pivot` | Normalized rotation point; default `{ x: 0.5, y: 0.5 }` (center) |
|
|
153
154
|
|
|
154
155
|
```tsx
|
|
155
156
|
<Sprite src="/player.png" x={100} y={80} width={64} height={64} />
|
|
@@ -157,6 +158,13 @@ Displays an image or a sprite-sheet animation. Supply exactly one of `src` or `a
|
|
|
157
158
|
|
|
158
159
|
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
160
|
|
|
161
|
+
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:
|
|
162
|
+
|
|
163
|
+
```tsx
|
|
164
|
+
<Sprite src="/sword.png" x={100} y={80}
|
|
165
|
+
pivot={{ x: 0.5, y: 0.9 }} rotation={45} />
|
|
166
|
+
```
|
|
167
|
+
|
|
160
168
|
### `Text`
|
|
161
169
|
|
|
162
170
|
Draws left-aligned, top-aligned text in the supplied `color`, or white by default. Uses `sans-serif` unless a font family is supplied.
|
|
@@ -258,7 +266,8 @@ A stateful moving body. Put drawing components and one or more `Bounds` inside i
|
|
|
258
266
|
| `forces` | `[]` | Force vectors in newtons, applied each frame |
|
|
259
267
|
| `drag` | `0` | Exponential velocity damping per second |
|
|
260
268
|
| `restitution` | `1` | Bounce factor; `0` removes bounce; a pair uses the lower factor |
|
|
261
|
-
| `
|
|
269
|
+
| `interactionMode` | `"body"` | Selects whether interaction settings belong to the body or its bounds |
|
|
270
|
+
| `layer` | Unset | Layer name used by other colliders' filters; body mode only |
|
|
262
271
|
| `collidesWith` | `[]` | Layers eligible for physical collision |
|
|
263
272
|
| `hitsWith` | `[]` | Layers to report overlap with, without requiring physical response |
|
|
264
273
|
| `ref` | Unset | Key returned by `gameRef` |
|
|
@@ -267,6 +276,13 @@ A stateful moving body. Put drawing components and one or more `Bounds` inside i
|
|
|
267
276
|
|
|
268
277
|
Physics treats one world unit as one centimeter. The renderer displays one unit as one CSS pixel.
|
|
269
278
|
|
|
279
|
+
Choose one place for interaction settings per body:
|
|
280
|
+
|
|
281
|
+
- 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.
|
|
282
|
+
- 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.
|
|
283
|
+
|
|
284
|
+
The mode selects interaction settings only. Bounds still belong to the body; movement, mass, restitution, and contact-hook identity remain at body level.
|
|
285
|
+
|
|
270
286
|
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
287
|
|
|
272
288
|
### `Bounds`
|
|
@@ -282,14 +298,26 @@ Defines collision geometry owned by its containing body. Choose either rectangle
|
|
|
282
298
|
|
|
283
299
|
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
300
|
|
|
301
|
+
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:
|
|
302
|
+
|
|
303
|
+
```tsx
|
|
304
|
+
<RigidBody2D key="platform" y={300} mass={0} interactionMode="bounds">
|
|
305
|
+
<Bounds width={200} height={20}
|
|
306
|
+
layer="ground" collidesWith={["player"]} />
|
|
307
|
+
<Bounds width={200} height={40} position={{ x: 0, y: -40 }}
|
|
308
|
+
layer="sensor" hitsWith={["player"]} />
|
|
309
|
+
</RigidBody2D>
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
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.
|
|
313
|
+
|
|
285
314
|
### `gameCollision(key, handler)` and `gameHit(key, handler)`
|
|
286
315
|
|
|
287
|
-
Call these each frame with the body's public `key`.
|
|
316
|
+
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
317
|
|
|
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.
|
|
318
|
+
- Physical collisions require both contacting bounds' effective `collidesWith` lists to include the other's effective layer. Both layers are defined for a physical collision.
|
|
319
|
+
- 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.
|
|
320
|
+
- 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
321
|
- Hits alone do not separate bodies or change their velocities.
|
|
294
322
|
- 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
323
|
|
|
@@ -299,8 +327,10 @@ function PhysicsExample() {
|
|
|
299
327
|
if (otherLayer === "world") console.log("Ball contacted world body:", otherKey);
|
|
300
328
|
});
|
|
301
329
|
|
|
302
|
-
gameHit("ball", (otherKey, otherLayer) => {
|
|
303
|
-
if (otherLayer === "world")
|
|
330
|
+
gameHit("ball", (otherKey, otherLayer, ownLayer) => {
|
|
331
|
+
if (otherLayer === "world") {
|
|
332
|
+
console.log("Ball overlapped world body:", otherKey, "using layer:", ownLayer);
|
|
333
|
+
}
|
|
304
334
|
});
|
|
305
335
|
|
|
306
336
|
return (
|
|
@@ -424,13 +454,133 @@ Returns the canvas's current CSS size as `{ width, height }`. Use this for respo
|
|
|
424
454
|
const { width, height } = gameViewport();
|
|
425
455
|
```
|
|
426
456
|
|
|
457
|
+
## Asynchronous operations
|
|
458
|
+
|
|
459
|
+
### `gameAsync(promise)`
|
|
460
|
+
|
|
461
|
+
Starts an asynchronous operation and returns a typed string ID. Pass a function returning a promise, rather than an already-started promise. The function is invoked in a microtask after the current synchronous code finishes. Both synchronous throws from that function and promise rejections are recorded as failures.
|
|
462
|
+
|
|
463
|
+
Call `gameAsync` when you want to start an operation, such as inside an input handler or an effect. Each call starts a new operation and returns a fresh ID. Store the ID across frames; starting the operation unconditionally in the root function would start it again every frame.
|
|
464
|
+
|
|
465
|
+
### `gameAsyncThen(id, handler)`, `gameAsyncCatch(id, handler)`, and `gameAsyncFinally(id, handler)`
|
|
466
|
+
|
|
467
|
+
Call these each frame to check the operation identified by the ID. They invoke handlers immediately when a matching completion is available; they do not install persistent listeners or return promises.
|
|
468
|
+
|
|
469
|
+
| Hook | Handler argument | When it runs |
|
|
470
|
+
| --- | --- | --- |
|
|
471
|
+
| `gameAsyncThen` | Resolved value, with its inferred type | Success |
|
|
472
|
+
| `gameAsyncCatch` | Rejection reason or thrown value, typed as `unknown` | Failure |
|
|
473
|
+
| `gameAsyncFinally` | None | Success or failure |
|
|
474
|
+
|
|
475
|
+
Completions are buffered and become available at the start of the next animation frame after settlement. Each completion is available for that one frame only. Every matching hook call in that frame can read it; reading does not consume it. If a matching hook is not called during that frame, it misses the completion.
|
|
476
|
+
|
|
477
|
+
Handlers run within the synchronous game frame and can use values captured from that frame, rather than the frame when the operation started. The result itself still belongs to the original operation. Watching only the current request ID lets you ignore results from superseded requests; it does not cancel those requests.
|
|
478
|
+
|
|
479
|
+
```tsx
|
|
480
|
+
function LoadedMessage() {
|
|
481
|
+
const [, setMessage, getMessage] = gameState("message.text", "Loading...");
|
|
482
|
+
const [, setRequest, getRequest] = gameState<{
|
|
483
|
+
id: ReturnType<typeof gameAsync<string>> | null;
|
|
484
|
+
}>("message.request", { id: null });
|
|
485
|
+
|
|
486
|
+
gameEffect("message.load", () => {
|
|
487
|
+
const id = gameAsync(async () => {
|
|
488
|
+
const response = await fetch("/message.txt");
|
|
489
|
+
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
|
|
490
|
+
return response.text();
|
|
491
|
+
});
|
|
492
|
+
setRequest({ id });
|
|
493
|
+
}, []);
|
|
494
|
+
|
|
495
|
+
const requestId = getRequest().id;
|
|
496
|
+
if (requestId !== null) {
|
|
497
|
+
gameAsyncThen(requestId, message => {
|
|
498
|
+
// message is inferred as string from the producer's return type.
|
|
499
|
+
setMessage(message);
|
|
500
|
+
});
|
|
501
|
+
gameAsyncCatch(requestId, error => {
|
|
502
|
+
setMessage(error instanceof Error ? error.message : "Could not load message.");
|
|
503
|
+
});
|
|
504
|
+
gameAsyncFinally(requestId, () => setRequest({ id: null }));
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
return <Text value={getMessage()} />;
|
|
508
|
+
}
|
|
509
|
+
```
|
|
510
|
+
|
|
511
|
+
The ID retains the resolved value's type for `gameAsyncThen`; widening it to plain `string` loses that connection. `AsyncId` is not a public named type export from `discodreamer`. Let IDs be inferred, or use `ReturnType<typeof gameAsync<ResultType>>` when declaring a type that stores an ID. When storing an ID in `gameState`, wrap it in an object as shown: the state's shallow `Readonly` return type then preserves the ID's string compatibility and result type. Rejection reasons remain `unknown` and should be narrowed before use. These hooks do not cancel operations or expose a pending status; native promises can also be used directly when frame-based delivery is not needed.
|
|
512
|
+
|
|
513
|
+
## Timer hooks
|
|
514
|
+
|
|
515
|
+
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.
|
|
516
|
+
|
|
517
|
+
### `gameTimeOut(key)`
|
|
518
|
+
|
|
519
|
+
Returns the readonly tuple `[start, when, clear, timeRemaining]`.
|
|
520
|
+
|
|
521
|
+
| Function | Behavior |
|
|
522
|
+
| --- | --- |
|
|
523
|
+
| `start(duration)` | Sets a deadline `duration` milliseconds from now, replacing any previous deadline |
|
|
524
|
+
| `when(handler, autoClear = true)` | Calls `handler()` if the deadline has been reached |
|
|
525
|
+
| `clear()` | Makes the timeout inactive |
|
|
526
|
+
| `timeRemaining()` | Returns milliseconds until the deadline, clamped to `0`, or `null` when inactive |
|
|
527
|
+
|
|
528
|
+
The timeout starts inactive. By default, `when` clears it before calling the handler, so it fires once and the handler can safely restart it. With `autoClear: false`, it stays expired and every subsequent `when` call fires until it is cleared or restarted, including repeated calls in the same frame. A later firing with `autoClear: true` also clears it.
|
|
529
|
+
|
|
530
|
+
`start`, `clear`, and `timeRemaining` use live stored state, so changes are visible to subsequent calls in the same frame. A zero or negative duration is already due on the next `when` call, which can be in that same frame. A timeout that expires between frames is handled on the first subsequent call to `when`.
|
|
531
|
+
|
|
532
|
+
```ts
|
|
533
|
+
const [startTimeout, whenTimeout, clearTimeout, timeRemaining] =
|
|
534
|
+
gameTimeOut("notice.timeout");
|
|
535
|
+
|
|
536
|
+
gameEvent("keyDown", ({ key }) => {
|
|
537
|
+
if (key === "n") startTimeout(2000);
|
|
538
|
+
if (key === "Escape") clearTimeout();
|
|
539
|
+
});
|
|
540
|
+
|
|
541
|
+
whenTimeout(() => sendMessage("notice.expired", null));
|
|
542
|
+
const remaining = timeRemaining(); // number | null
|
|
543
|
+
```
|
|
544
|
+
|
|
545
|
+
### `gameInterval(key)`
|
|
546
|
+
|
|
547
|
+
Returns the readonly tuple `[start, when, clear]`.
|
|
548
|
+
|
|
549
|
+
| Function | Behavior |
|
|
550
|
+
| --- | --- |
|
|
551
|
+
| `start(duration)` | Starts or restarts with a new duration and resets the run index to `0` |
|
|
552
|
+
| `when(handler)` | Calls `handler(run)` once for each tick due since the previous check |
|
|
553
|
+
| `clear()` | Stops the interval and resets its run count |
|
|
554
|
+
|
|
555
|
+
The interval starts inactive. Durations must be finite and greater than zero; otherwise `start` throws without replacing the current interval. The first tick is due after one full duration, with a zero-based run index: `0`, `1`, `2`, and so on.
|
|
556
|
+
|
|
557
|
+
Missed ticks are delivered together on the next `when` call. For example, an interval started with `1000` milliseconds and first checked after `3500` milliseconds calls the handler with `0`, `1`, and `2`. A second check at the same time does not repeat those ticks. Timing stays anchored to the start time rather than being reset after each check.
|
|
558
|
+
|
|
559
|
+
If a handler clears or restarts the interval, the remaining callbacks from the old batch stop. Restarting also resets numbering, including when the duration and start timestamp match the previous interval. After a long pause, catch-up can run many callbacks in one frame. Wall-clock timers continue to age while frames are suspended; they are not automatically paused with game logic.
|
|
560
|
+
|
|
561
|
+
```ts
|
|
562
|
+
const [startInterval, whenInterval, clearInterval] =
|
|
563
|
+
gameInterval("enemy.spawn.interval");
|
|
564
|
+
|
|
565
|
+
gameEffect("enemy.spawn.start", () => startInterval(1000), []);
|
|
566
|
+
|
|
567
|
+
gameEvent("keyDown", ({ key }) => {
|
|
568
|
+
if (key === "p") clearInterval();
|
|
569
|
+
if (key === "r") startInterval(1000);
|
|
570
|
+
});
|
|
571
|
+
|
|
572
|
+
whenInterval(run => sendMessage("enemy.spawn", { run }));
|
|
573
|
+
```
|
|
574
|
+
|
|
575
|
+
Use an ordinary key for `gameInterval`, not a `$` literal key: the interval stores several independent numbered state slots under that key.
|
|
576
|
+
|
|
427
577
|
## Animation and image hooks
|
|
428
578
|
|
|
429
579
|
### `gameAnimation(key, animations, config)`
|
|
430
580
|
|
|
431
581
|
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.
|
|
432
582
|
|
|
433
|
-
Config requires `src` and `size
|
|
583
|
+
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.
|
|
434
584
|
|
|
435
585
|
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.
|
|
436
586
|
|
|
@@ -447,6 +597,19 @@ function AnimatedPlayer({ moving }: { moving: boolean }) {
|
|
|
447
597
|
|
|
448
598
|
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.
|
|
449
599
|
|
|
600
|
+
For rectangular frames, configure the source dimensions independently from the display size:
|
|
601
|
+
|
|
602
|
+
```tsx
|
|
603
|
+
const animation = gameAnimation("character.animation", [
|
|
604
|
+
[true, [0, 1, 2, 3]],
|
|
605
|
+
], { src: "/character-sheet.png", size: { width: 32, height: 48 } });
|
|
606
|
+
|
|
607
|
+
// Display each 32 × 48 source frame at twice its size:
|
|
608
|
+
return <Sprite animation={animation} width={64} height={96} />;
|
|
609
|
+
```
|
|
610
|
+
|
|
611
|
+
If `Sprite` display dimensions are omitted, they default to the source frame dimensions. Numeric `size` values continue to work unchanged.
|
|
612
|
+
|
|
450
613
|
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.
|
|
451
614
|
|
|
452
615
|
### `gameImage(src)`
|