@maccesar/titools 4.15.0 → 4.16.0

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.
@@ -1,1679 +0,0 @@
1
- # ti.game recipes by genre
2
-
3
- Working patterns distilled from the 26 official demos in `example/` and from a shipped Alloy game (Titanium Lander). Each recipe shows the part that is specific to the genre; the shared scaffolding is in [The scaffolding](#the-scaffolding) and is not repeated.
4
-
5
- Every snippet uses only API that exists in upstream `main` at `ee69056`, 2026-08-27 (manifest `0.5.0` — the number moved with this release, but it has sat still through whole feature sets before, so date the build). Check [roadmap.md](roadmap.md) before reaching for anything not shown here.
6
-
7
- <!-- TOC-START -->
8
- ## Contents
9
-
10
- - [The 32 demos, and what each one is the reference for](#the-32-demos-and-what-each-one-is-the-reference-for)
11
- - [The scaffolding](#the-scaffolding)
12
- - [Cross-cutting patterns](#cross-cutting-patterns)
13
- - [Tap-to-flap](#tap-to-flap)
14
- - [Platformer](#platformer)
15
- - [Top-down / Zelda](#top-down--zelda)
16
- - [Top-down racer](#top-down-racer)
17
- - [Asteroids / space shooter](#asteroids--space-shooter)
18
- - [Lunar lander](#lunar-lander)
19
- - [Endless runner](#endless-runner)
20
- - [Rhythm game](#rhythm-game)
21
- - [Ball sports / breakout physics](#ball-sports--breakout-physics)
22
- - [Cards and board games](#cards-and-board-games)
23
- - [Point & click adventure](#point--click-adventure)
24
- - [Particles](#particles)
25
- - [Ropes and chains](#ropes-and-chains)
26
- - [Camera work](#camera-work)
27
- - [Visual effects](#visual-effects)
28
-
29
- <!-- TOC-END -->
30
-
31
- ## The 32 demos, and what each one is the reference for
32
-
33
- `example/` is the module's real documentation: every demo is a runnable app, and upstream keeps them current with the engine. When a recipe here is not enough, open the demo — it compiles today.
34
-
35
- | Demo | The reference implementation of | Covered here |
36
- | --- | --- | --- |
37
- | `basic.js` | Sheets, animations, drag/pinch/rotate, tween chaining | [The scaffolding](#the-scaffolding) |
38
- | `puzzle.js` | Drag & drop with snapping, press-to-lift, one piece per finger | [Cards and board games](#cards-and-board-games) |
39
- | `flappy.js` | Gravity + tap impulse, score zones, wrapping parallax | [Tap-to-flap](#tap-to-flap) |
40
- | `platformer.js` | `solidWith`, `land`, `oneWay` stairs, a moving platform that carries you, d-pad | [Platformer](#platformer) |
41
- | `volley.js` | `restitution`, JS hit response, an AI timer | [Ball sports / breakout physics](#ball-sports--breakout-physics) |
42
- | `racing.js` | `carMode` drift, skid marks, lap and checkpoint logic | [Top-down racer](#top-down-racer) |
43
- | `cards.js` | Deck dealing, fanned hand, selection tweens, idle wobble | [Cards and board games](#cards-and-board-games) |
44
- | `asteroids.js` | `thrust`/`angularVelocity`, `wrapAround`, bullet pooling, additive bolts | [Asteroids / space shooter](#asteroids--space-shooter) |
45
- | `topdown.js` | Tile map from a string array, `ySort` depth, follower NPC | [Top-down / Zelda](#top-down--zelda) |
46
- | `skate.js` | Endless runner: pooled obstacles, jump button, pixel-art parallax | [Endless runner](#endless-runner) |
47
- | `pointclick.js` | Tap-to-walk with `findPath` + `followPath`, verb coin, hotspots | [Point & click adventure](#point--click-adventure) |
48
- | `particles.js` | Fountain, tap bursts, a smoke trail following a dragged sprite | [Particles](#particles) |
49
- | `rhythm.js` | Pooled notes on native velocity, `press` pads, timing windows | [Rhythm game](#rhythm-game) |
50
- | `camera.js` | Dead-zone follow, `cameraBounds`, zoom, shake, `cameraEffect`, `scrollFactor` | [Camera work](#camera-work) |
51
- | `rope.js` | Verlet ropes from a dragged head and from a fixed anchor | [Ropes and chains](#ropes-and-chains) |
52
- | `flip.js` | `flipX`/`flipY` driven by movement; tap inverts gravity | [Visual effects](#visual-effects) |
53
- | `hitbox.js` | `debug: true` overlays, and why the per-axis hitbox scales exist | [Seeing the hitbox](#seeing-the-hitbox--hitboxjs) |
54
- | `blend.js` | The four blend modes side by side, `flash()` variants | [Visual effects](#visual-effects) |
55
- | `text.js` | Screen-fixed HUD, world-space labels, text buttons, wrapped dialog, a name tag pinned with `attachTo` | [HUD](#hud--textjs-flappyjs), [Labels pinned to a sprite](#labels-bars-and-turrets-pinned-to-a-sprite--attachto-textjs) |
56
- | `swept.js` | `swept: true` vs tunneling, same bullets, rising speed | [Object pooling](#object-pooling) |
57
- | `path.js` | Smoothed circuits, sharp patrols, `play(name, { then })` chains | [Patrol routes and animation chains](#patrol-routes-and-animation-chains--pathjs) |
58
- | `raycast.js` | Line of sight, ledge probes, tap-fired hitscan | [Line of sight, ledge probes and hitscan](#line-of-sight-ledge-probes-and-hitscan--raycastjs) |
59
- | `zones.js` | The `collision`/`collisionend` lifecycle, including despawned partners | [Zones you can be inside of](#zones-you-can-be-inside-of-enter--exit--zonesjs) |
60
- | `demoscene.js` | Sine scrollers and copper bars built from `followPath` circles | [Visual effects](#visual-effects) |
61
- | `maze.js` | A* over a tile maze, `simplify: false` route visualization, a re-pathing hound | [Pathfinding around obstacles](#pathfinding-around-obstacles--mazejs-pointclickjs) |
62
- | `timescale.js` | `timeScale` slow motion and freeze; game clock vs `setInterval` | [Timers on the game clock](#timers-on-the-game-clock) |
63
- | `circles.js` | The three hitbox shapes as **solids**, side by side, plus `'block'` vs `'push'` on the same shot | [Shaped solids](#shaped-solids-ramps-round-posts-and-bodies-that-push-back--slopesjs-circlesjs-pooljs-drumjs) |
64
- | `slopes.js` | Tilted `'rotatedRect'` ramps with a rect rider and a circle rider, and `restitution` living on the surface | [Shaped solids](#shaped-solids-ramps-round-posts-and-bodies-that-push-back--slopesjs-circlesjs-pooljs-drumjs) |
65
- | `plinko.js` | 86 circular solids: why a peg has to be a circle and not its bounding box | [Shaped solids](#shaped-solids-ramps-round-posts-and-bodies-that-push-back--slopesjs-circlesjs-pooljs-drumjs) |
66
- | `pool.js` | `solidMode: 'push'` bodies exchanging momentum, `linearDamping` as felt | [Shaped solids](#shaped-solids-ramps-round-posts-and-bodies-that-push-back--slopesjs-circlesjs-pooljs-drumjs) |
67
- | `drum.js` | `solidMode: 'contain'`: 25 balls inside one analytic circle, no wall segments | [Shaped solids](#shaped-solids-ramps-round-posts-and-bodies-that-push-back--slopesjs-circlesjs-pooljs-drumjs) |
68
- | `wind.js` | `gravityX` as wind, and as the lean of a top-down table | [Shaped solids](#shaped-solids-ramps-round-posts-and-bodies-that-push-back--slopesjs-circlesjs-pooljs-drumjs) |
69
-
70
- ## The scaffolding
71
-
72
- Every game repeats this shape. Sheets and sounds are created once, outside `resize`, because they are texture handles, not scene objects.
73
-
74
- ```javascript
75
- const Game = require('ti.game');
76
-
77
- module.exports = function () {
78
-
79
- const win = Ti.UI.createWindow({
80
- backgroundColor: '#000',
81
- theme: 'Theme.Titanium.DayNight.NoTitleBar'
82
- });
83
- const gameView = Game.createGameView({
84
- backgroundColor: '#8ed8f8',
85
- maxFps: 60
86
- // debug: true // draw every collision shape while tuning hitboxes
87
- });
88
-
89
- const heroSheet = Game.createSpriteSheet({ image: 'assets/hero.png', frameWidth: 64, frameHeight: 64 });
90
- const jumpSound = Game.createSound({ url: 'assets/jump.wav', volume: 0.8 });
91
-
92
- let timer = null;
93
- win.addEventListener('close', () => {
94
- if (timer !== null) {
95
- clearInterval(timer);
96
- timer = null;
97
- }
98
- });
99
-
100
- let initialized = false;
101
- gameView.addEventListener('resize', (e) => {
102
- if (initialized) {
103
- return;
104
- }
105
- initialized = true;
106
- init(e.width, e.height);
107
- });
108
-
109
- function init(W, H) {
110
- // The whole game lives here. Derive every size from W and H so the
111
- // layout holds on any screen: SPEED = W * 0.35, GRAVITY = H * 2.2.
112
- }
113
-
114
- win.add(gameView);
115
- win.open();
116
- };
117
- ```
118
-
119
- Sizing everything as a fraction of `W`/`H` is not cosmetic — a jump tuned in absolute pixels becomes unplayable on a different device. The demos consistently express speeds as `W * f`, accelerations as `H * f` and sprite sizes as `Math.min(W, H) * f`.
120
-
121
- ## Cross-cutting patterns
122
-
123
- The pieces every genre below reuses: pooling, freeing a level's textures, parallax, multitouch controls, HUD text, wrapped dialog, labels and bars attached to a sprite, invisible triggers, seeing the hitbox, enter/exit zones, patrol routes, line of sight, pathfinding, game-clock timers and hit-stop.
124
-
125
- ### Object pooling
126
-
127
- Create a fixed set once, recycle forever. `visible = false` also removes the sprite from collision, which is what makes this work.
128
-
129
- ```javascript
130
- const bullets = [];
131
- for (let i = 0; i < 10; i++) {
132
- const sprite = Game.createSprite({
133
- sheet: shipSheet,
134
- frame: 3,
135
- width: 8,
136
- height: 16,
137
- visible: false,
138
- wrapAround: true,
139
- swept: true, // path-tested: a fast bolt cannot skip past a rock
140
- collidesWith: ['asteroid']
141
- });
142
- const state = { sprite: sprite, active: false, generation: 0 };
143
-
144
- sprite.addEventListener('collision', (e) => {
145
- if (!state.active) {
146
- return;
147
- }
148
- deactivate(state);
149
- e.other.visible = false; // the rock is gone: no render, no collision
150
- });
151
-
152
- gameView.add(sprite);
153
- bullets.push(state);
154
- }
155
-
156
- function deactivate(state) {
157
- state.active = false;
158
- state.sprite.visible = false;
159
- state.sprite.velocityX = 0;
160
- state.sprite.velocityY = 0;
161
- }
162
-
163
- function fire(x, y, vx, vy) {
164
- const state = bullets.find((b) => !b.active);
165
- if (!state) {
166
- return; // pool exhausted — drop the shot
167
- }
168
- state.active = true;
169
- state.generation++;
170
- const generation = state.generation;
171
- Object.assign(state.sprite, { x: x, y: y, velocityX: vx, velocityY: vy, visible: true });
172
- setTimeout(() => {
173
- // burn out — unless this slot was already recycled by a newer shot
174
- if (state.active && state.generation === generation) {
175
- deactivate(state);
176
- }
177
- }, 1200);
178
- }
179
- ```
180
-
181
- The `generation` counter matters: without it, a timeout fired for an old shot deactivates the *new* bullet occupying that slot.
182
-
183
- `swept: true` (compared side by side in `swept.js`) is what keeps a fast bolt from crossing a rock between two frames without ever overlapping it. The asteroids demo predates it and inflates the hitbox instead (`hitboxScale: 1.4`) — that works, at the price of counting near misses as hits. Prefer `swept`, and reserve `hitboxScale` — with `hitboxScaleX`/`hitboxScaleY` when the art's fit differs per axis — for fairness tuning.
184
-
185
- Recycling a sprite with `visible = false` fires `collisionend` on anything it was touching. Handlers that treat separation as "the player walked away" need to tolerate a despawn.
186
-
187
- ### Freeing a level's textures
188
-
189
- Pooling recycles sprites; it does not free the **texture** behind them. A game that streams worlds accumulates every atlas it has ever loaded until the GL context dies. `unload()` releases one on the next rendered frame.
190
-
191
- ```javascript
192
- function unloadLevel(level) {
193
- level.sprites.forEach((s) => gameView.remove(s));
194
- level.sheets.forEach((sheet) => sheet.unload()); // only once nothing draws from them
195
- }
196
- ```
197
-
198
- It is permanent — not an eviction that reloads on demand. A sprite still pointing at an unloaded sheet stops drawing, silently. A single-level game should not call it: the textures die with the window.
199
-
200
- ### Parallax
201
-
202
- Two ways, and the choice is decided by whether the **camera** moves or the **world** does.
203
-
204
- **A camera travelling through a static world** — platformer, top-down, anything using `follow()` — wants `scrollFactor`, one property per layer:
205
-
206
- ```javascript
207
- const clouds = Game.createSprite({ sheet: cloudSheet, x: W / 2, y: 120, zIndex: 0, scrollFactor: 0.25 });
208
- const hills = Game.createSprite({ sheet: hillSheet, x: W / 2, y: 260, zIndex: 1, scrollFactor: 0.6 });
209
- const sun = Game.createSprite({ sheet: sunSheet, x: 60, y: 60, zIndex: 0, scrollFactor: 0 });
210
- ```
211
-
212
- `0` pins the sun to the view while still zooming with `cameraScale` — that is the difference from `screenFixed`, which ignores zoom as well. Values above `1` overtake the camera for foreground grass. The sprite's `x`/`y` never change: `scrollFactor` shifts where it is *drawn* and maps touch back to match, so collisions still happen at the world coordinates you wrote.
213
-
214
- **A world scrolling under a fixed camera** — endless runner, flappy — cannot use `scrollFactor`, because the camera never travels. Two screen-wide copies per layer, scrolled by native velocity; `wrapX`/`wrapShift` teleport a copy that left the screen back behind its sibling. No JS runs in the loop.
215
-
216
- ```javascript
217
- function makeLayer(sheet, y, height, speed, z) {
218
- const copies = [];
219
- for (let i = 0; i < 2; i++) {
220
- const s = Game.createSprite({
221
- sheet: sheet,
222
- x: W / 2 + i * W,
223
- y: y,
224
- width: W,
225
- height: height,
226
- zIndex: z,
227
- tileRepeat: 'x', // keeps texture density; needs repeat: true on the sheet
228
- wrapX: -W / 2,
229
- wrapShift: 2 * W
230
- });
231
- gameView.add(s);
232
- copies.push(s);
233
- }
234
- return {
235
- setSpeed: (v) => copies.forEach((copy) => {
236
- copy.velocityX = -v;
237
- })
238
- };
239
- }
240
-
241
- const skyline = makeLayer(skylineSheet, groundTop - SKY_H / 2, SKY_H, SPEED * 0.12, 1);
242
- const street = makeLayer(streetSheet, (groundTop + H) / 2, H - groundTop, SPEED, 8);
243
- ```
244
-
245
- Slower layers read as further away. Three layers (clouds at 0.15×, hills at 0.4×, ground at 1×) is the flappy demo's recipe. `camera.js` demos the other half: `scrollFactor` cloud shadows at 1.35× and a `scrollFactor: 0` sun.
246
-
247
- ### Multitouch on-screen controls
248
-
249
- Each button must be **its own Titanium view** — sibling views receive simultaneous pointers, so holding a direction while pressing jump works. A single container splitting touches itself does not.
250
-
251
- ```javascript
252
- function makeButton(title, position, fontSize) {
253
- const button = Ti.UI.createLabel({
254
- text: title,
255
- textAlign: 'center',
256
- color: '#fff',
257
- font: { fontSize: fontSize || 30, fontWeight: 'bold' },
258
- backgroundColor: '#59000000',
259
- borderRadius: 40,
260
- width: '80dp',
261
- height: '80dp',
262
- bottom: '24dp'
263
- });
264
- // Manual press feedback: touchFeedback's ripple cannot animate over this
265
- // canvas and spams RippleDrawable errors on Android.
266
- button.addEventListener('touchstart', () => {
267
- button.backgroundColor = '#8c000000';
268
- });
269
- ['touchend', 'touchcancel'].forEach((event) => {
270
- button.addEventListener(event, () => {
271
- button.backgroundColor = '#59000000';
272
- });
273
- });
274
- Object.assign(button, position);
275
- return button;
276
- }
277
-
278
- function bindHold(button, apply, release) {
279
- button.addEventListener('touchstart', apply);
280
- ['touchend', 'touchcancel'].forEach((event) => {
281
- button.addEventListener(event, release);
282
- });
283
- }
284
-
285
- const leftButton = makeButton('◀', { left: '24dp' });
286
- bindHold(leftButton, () => {
287
- car.steering = -1;
288
- }, () => {
289
- if (car.steering === -1) { // don't cancel the other button's input
290
- car.steering = 0;
291
- }
292
- });
293
- ```
294
-
295
- The guard in the release handler is what keeps two opposite buttons from fighting: releasing left only zeroes steering if left is still the active direction.
296
-
297
- ### HUD — `text.js`, `flappy.js`
298
-
299
- Text sprites with `screenFixed: true`. They live in the scene — one batch, no overlay views — but ignore the camera, so a score stays in the corner while the world scrolls under it.
300
-
301
- ```javascript
302
- // Created outside resize (no size known yet), positioned once it is
303
- const scoreLabel = Game.createText({ text: '0', screenFixed: true, zIndex: 100 });
304
- const statusLabel = Game.createText({ text: 'Tap to start!', screenFixed: true, zIndex: 100 });
305
-
306
- function buildLevel(W, H) {
307
- const TEXT_SCALE = Math.max(1, Math.round(W / 240)); // integer: crisp pixels
308
- Object.assign(scoreLabel, { scale: TEXT_SCALE, x: W / 2, y: H * 0.08 });
309
- Object.assign(statusLabel, { scale: TEXT_SCALE, x: W / 2, y: H * 0.45 });
310
- gameView.add([scoreLabel, statusLabel]);
311
- // ...
312
- }
313
-
314
- function score() {
315
- points += 1;
316
- scoreLabel.text = points + ' / ' + GATE_COUNT;
317
- scoreLabel.flash('#4dff88', 250); // text flashes like any sprite
318
- }
319
- ```
320
-
321
- Scaling from `W` is what replaces `fontSize`: a bitmap font has one native size, and an integer multiplier is the only way to keep texels square. `Math.max(1, ...)` guards the smallest screens.
322
-
323
- Because a label is a sprite, the HUD gets the whole toolbox for free — `animate()` to pop a score on change, `tintColor` per state, `glowColor` on a title, `idleAnimation` for a gentle wobble, and `tap` handlers so a `[ RESET ]` label works as a button with no Titanium view behind it.
324
-
325
- Drop `screenFixed` and the same label becomes world furniture: signposts, floating damage numbers, a name over an NPC — it scrolls with everything else.
326
-
327
- A dialog box is one long string with `maxWidth`: the engine breaks the lines on word boundaries and re-wraps every time `text` is written, so the source keeps no hand-placed `\n`.
328
-
329
- ```javascript
330
- const UNIT = Math.max(1, Math.round(W / 240));
331
- const dialog = Game.createText({
332
- text: 'TAP FOR POND WISDOM',
333
- maxWidth: Math.round(W * 0.55 / UNIT), // font-space px: divide by the scale
334
- align: 'center',
335
- lineSpacing: 1.3,
336
- scale: UNIT,
337
- x: W / 2,
338
- y: H * 0.78,
339
- zIndex: 3
340
- });
341
- dialog.addEventListener('tap', () => {
342
- dialog.text = lines[i++ % lines.length]; // re-wraps natively
343
- dialog.flash('#fff', 150);
344
- });
345
- ```
346
-
347
- `maxWidth` is measured before `scale`, which is the only trap here — pass screen pixels straight in and the block comes out `scale` times too wide. `align` positions the lines against each other (the block's own width), not inside the wrap column, so anchor the sprite where the text should sit. A word longer than `maxWidth` overflows instead of breaking mid-word.
348
-
349
- Overlaid `Ti.UI.Label` views remain the answer for text the engine's font cannot draw (accents, system fonts, right-to-left) and for real UI: menus, dialogs, text inputs.
350
-
351
- ### Labels, bars and turrets pinned to a sprite — `attachTo`, `text.js`
352
-
353
- A HUD is `screenFixed`; a name tag, a health bar or a shadow is the opposite — it belongs *on* a sprite that moves. `attachTo` is the native version of the JS everyone wrote before it: a timer copying `owner.x` into `tag.x`, one bridge round trip per tag per tick, and always a frame behind.
354
-
355
- ```javascript
356
- const tag = Game.createText({ text: 'THE BALL', scale: UNIT, tintColor: '#7fd4ff', zIndex: 6 });
357
- tag.attachTo(ball, { offsetY: -(W * 0.09) }); // offset in the tag's own units
358
- gameView.add(tag); // the tag is still a scene sprite
359
- ```
360
-
361
- The tag now tracks the ball through gravity, tweens, a moving platform and a finger drag, with no JS in the loop, and disappears with it — `gameView.remove(ball)` removes everything attached to the ball, recursively.
362
-
363
- A health bar is the same idea with two sprites, and shows where inheritance stops:
364
-
365
- ```javascript
366
- // blockSheet is any small opaque texture stretched and tinted — a sheet-less
367
- // sprite draws nothing at all, that is the invisible-trigger idiom below
368
- const barBack = Game.createSprite({ sheet: blockSheet, width: 40, height: 5, zIndex: 5, tintColor: '#222' });
369
- const barFill = Game.createSprite({ sheet: blockSheet, width: 40, height: 5, zIndex: 6, anchor: 'left', tintColor: '#3f6' });
370
-
371
- barBack.attachTo(hero, { offsetY: -34 });
372
- barFill.attachTo(hero, { offsetX: -20, offsetY: -34 }); // anchored left → grows to the right
373
- gameView.add([barBack, barFill]);
374
-
375
- // on damage: the width is yours to set — scale, visibility and tint are not inherited
376
- barFill.width = 40 * (hp / hpMax);
377
-
378
- // on death: one tween fades the hero AND both bars, because opacity does cascade
379
- hero.animate({ opacity: 0, duration: 400 });
380
- ```
381
-
382
- `rotate: true` is the other half: the offset swings around the target and the sprite copies its rotation, which is what a turret on a tank or a hat on a tumbling hero needs.
383
-
384
- ```javascript
385
- turret.attachTo(tank, { offsetY: -12, rotate: true });
386
- ```
387
-
388
- Four things to keep in mind:
389
-
390
- - **The attached sprite has to be added to the scene**, and so does its target. Neither pins otherwise — the sprite just sits at whatever `x`/`y` it was created with.
391
- - **Its position stops being yours.** Velocity, gravity and `animate({ x })` still run and are overwritten the same frame. To fling a tag off a dying enemy, `detach()` first, then give it velocity.
392
- - **Match `scrollFactor` between the two.** Attachment pins world coordinates; parallax changes only where a sprite is *drawn*. A tag at `scrollFactor: 1` on a background sprite at `0.5` stays pinned in world space and drifts across the screen anyway.
393
- - **A faded owner also stops its tags taking taps.** The inherited opacity runs through the hit test as well as the draw, so an owner at `opacity: 0` leaves an attached text button untouchable — while that button's own `opacity` still reads 1. Hide an owner with `visible = false` if the tags should keep working, or detach them.
394
-
395
- ### Invisible triggers
396
-
397
- A sprite with `width`/`height` and no `sheet` renders nothing but still collides. This is how scores, goals, ceilings, kill floors, walls and checkpoints are built.
398
-
399
- ```javascript
400
- // score zone in the gap between two pipes
401
- gameView.add(Game.createSprite({ x: gateX, y: gapCenter, width: 20, height: GAP, collisionGroup: 'score' }));
402
-
403
- // invisible ceiling so the player cannot escape upward
404
- gameView.add(Game.createSprite({ x: W / 2, y: -20, width: W * 3, height: 40, collisionGroup: 'ceiling' }));
405
-
406
- // side walls
407
- [-20, W + 20].forEach((x) => {
408
- gameView.add(Game.createSprite({ x: x, y: H / 2, width: 40, height: H * 3, collisionGroup: 'wall' }));
409
- });
410
- ```
411
-
412
- Attach your own metadata to a sprite and read it back from `e.other` in the handler:
413
-
414
- ```javascript
415
- const zone = Game.createSprite({ x: cp.x, y: cp.y, width: cp.w, height: cp.h, collisionGroup: 'checkpoint' });
416
- zone.cpIndex = index;
417
-
418
- car.addEventListener('collision', (e) => {
419
- if (e.group === 'checkpoint') {
420
- visited[e.other.cpIndex] = true;
421
- }
422
- });
423
- ```
424
-
425
- ### Seeing the hitbox — `hitbox.js`
426
-
427
- `debug: true` on the GameView is the whole tuning workflow, and the demo exists to make the overlays legible: two identical adventurers walk into the same wall, one untuned and one with `hitboxScaleX: 0.62` / `hitboxScaleY: 0.92`. The untuned one stops a body's width short and hovers above the floor on his frame's padding; the tuned one goes flush and lands his feet. Tapping toggles the tuning live, so the green box snaps between frame and drawing.
428
-
429
- ```javascript
430
- const gameView = Game.createGameView({ debug: true }); // green = collision AABB, blue = drawn frame, orange = anchor
431
-
432
- hero.hitboxScaleX = 0.62; // both are live: write them and watch the box move
433
- hero.hitboxScaleY = 0.92;
434
- ```
435
-
436
- Read the two boxes as a pair: green is what collides, blue is what draws **and what takes taps**. Green much smaller than blue on one axis only is exactly the case the per-axis scales exist for; green and blue identical on a sprite whose art has padding is the bug the demo dramatizes.
437
-
438
- The orange dot is the third variable, not decoration: the box shrinks **around the anchor**, so where the anchor sits decides which edge stays put. A prop that should collide from mid-height down while still resting on the floor is the anchor and the scale together, and both have a readable form now:
439
-
440
- ```javascript
441
- // the same thing, twice — the second one says what it is doing
442
- Game.createSprite({ sheet, anchorY: 1, hitboxScaleY: 0.55 });
443
- Game.createSprite({ sheet, anchor: 'bottom', hitboxScaleY: '55%' });
444
- ```
445
-
446
- Every ratio takes a percentage this way (`opacity`, `scale`, `scrollFactor`, `restitution`, `volume`, the `follow` margins…) and both anchors take names. Coordinates, sizes, degrees and speeds do not — they were never fractions.
447
-
448
- ### Shaped solids: ramps, round posts and bodies that push back — `slopes.js`, `circles.js`, `pool.js`, `drum.js`
449
-
450
- Until 2026-08-27 a solid was always resolved as an axis-aligned box no matter what it looked like, so a round post showed flat faces and a tilted ramp blocked along a phantom horizontal ledge. Now the **solid's** declared shape takes part, which turns four hand-written workarounds into one property.
451
-
452
- **A ramp is one turned rectangle**, not a staircase of small ones:
453
-
454
- ```javascript
455
- const ramp = Game.createSprite({
456
- sheet: wallSheet, x: W * 0.28, y: H * 0.24,
457
- width: W * 0.30, height: 14,
458
- rotation: 12,
459
- hitboxShape: 'rotatedRect', // the box turns with the art
460
- collisionGroup: 'ramp'
461
- });
462
-
463
- const crate = Game.createSprite({
464
- sheet: crateSheet, x: W * 0.2, y: 0,
465
- gravity: 1400, swept: true,
466
- solidWith: ['ramp']
467
- });
468
- ```
469
-
470
- The rider needs nothing new — `'rect'` against a `'rotatedRect'` goes through separating axes on its own, and a circle rider is taken into the ramp's frame. Both settle on the real face and slide. Keep ramps **short**: a rider that slides a long one arrives at the bottom carrying everything the drop gave it and leaves like a projectile, which reads as the ramp firing it.
471
-
472
- **A round obstacle wants a circle on the solid, not just on the ball.** `hitboxShape: 'circle'` on the mover has been there for a while; putting it on the *peg* is what makes the contact normal run centre to centre:
473
-
474
- ```javascript
475
- const peg = Game.createSprite({ sheet, x, y, hitboxShape: 'circle', collisionGroup: 'peg' });
476
-
477
- const chip = Game.createSprite({
478
- sheet, hitboxShape: 'circle', gravity: 1200,
479
- restitution: 0.42,
480
- swept: true, // small pegs, fast chip: no stepping over one
481
- collisionGroup: 'chip',
482
- solidWith: ['peg', 'chip'],
483
- solidMode: 'push' // …and the chips are bodies to each other
484
- });
485
- ```
486
-
487
- As bounding boxes every peg is a square with a flat top and the chips stack instead of scattering. That is the whole Plinko board.
488
-
489
- **Balls that push each other** need agreement on both sides — this is the one setting that fails silently when it is half-configured:
490
-
491
- ```javascript
492
- const ball = Game.createSprite({
493
- sheet: ballSheet, hitboxShape: 'circle',
494
- restitution: 0.96,
495
- linearDamping: 0.62, // the felt: it trickles to a halt
496
- swept: true,
497
- collisionGroup: 'ball',
498
- solidWith: ['ball', 'rail'], // ← its own group is in there
499
- solidMode: 'push'
500
- });
501
- ```
502
-
503
- Every clause matters: both sprites `'push'`, both circles, and **each listing the other's group**. Drop any one and the pair quietly degrades to one ball shoving an immovable one, which looks like broken momentum and is a missing string. There are no masses and no spin — a marble and a boulder trade velocity identically.
504
-
505
- **A container is one sprite, not a ring of walls.** `solidMode: 'contain'` keeps matched circles *inside* a circle, analytically, so there are no seams to squeeze through and nothing to place by hand:
506
-
507
- ```javascript
508
- // sheetless: it collides and contains, and draws nothing — draw the barrel over it
509
- gameView.add(Game.createSprite({
510
- x: CX, y: CY, width: DRUM * 0.88, height: DRUM * 0.88,
511
- touchEnabled: false,
512
- hitboxShape: 'circle',
513
- solidMode: 'contain',
514
- collisionGroup: 'drum',
515
- debug: true // green circle = exactly where the wall is
516
- }));
517
-
518
- // the balls list the drum; the drum lists nothing — containment is one-directional
519
- const ball = Game.createSprite({
520
- sheet: ballSheet, hitboxShape: 'circle',
521
- gravity: 900, restitution: 0.55, linearDamping: 0.35,
522
- collisionGroup: 'ball', solidWith: ['drum', 'ball'], solidMode: 'push'
523
- });
524
- ```
525
-
526
- Two things bite here. The sweep **ignores** anything that is not `solidMode: 'block'`, so `swept: true` will not stop a fast enough ball crossing the boundary between frames — keep the speeds inside a container sane. And a `'contain'` solid only holds *circles*: a rect mover runs a resolver that never reads `solidMode` and gets pushed **out** of the boundary instead of held in.
527
-
528
- **`linearDamping` is the missing friction, with a caveat.** `drag` only ever worked inside `carMode`; this is the same idea for ordinary sprites, and it is what brings a pool table to rest. But nothing checks contact — it bleeds speed on both axes, in the air as much as on the felt, and along a slope as much as across it. Right for a table, wrong for a hill. Below a combined 4 px/s the engine zeroes the velocity outright, so a deliberate 3 px/s drift dies the moment that sprite also carries damping.
529
-
530
- **A bouncy surface is now a property of the surface.** `restitution` is read off both sides and mixed as `max`, so a springy floor rebounds riders that are not themselves bouncy:
531
-
532
- ```javascript
533
- addSurface({ color: '#4caf50', restitution: 0.5 }); // the floor and the side walls
534
- // the ball keeps restitution: 0.1 and still bounces off them at 0.5
535
- ```
536
-
537
- The cost of `max` is that it cannot be opted out of — a deliberately dead crate bounces off that floor too — and a rebound over 40 px/s takes the reflecting branch, which never sets `onGround` and never fires `land`. A jump gated on `onGround` stops working on the one platform somebody made bouncy.
538
-
539
- **`gravityX` is the sibling of `gravity`, not half of a vector.** `gravity` keeps its exact vertical meaning; this is a second constant acceleration on X, read natively every tick, so a field of leaves answers a wind change at once with no per-frame JS:
540
-
541
- ```javascript
542
- leaves.forEach((leaf) => { leaf.gravityX = wind; }); // on a button, not on a timer
543
- ```
544
-
545
- The other use has nothing to do with wind: a top-down table with `gravity: 0` and a non-zero `gravityX` is a board seen from above with a lean.
546
-
547
- ### Zones you can be inside of (enter / exit) — `zones.js`
548
-
549
- `collision` and `collisionend` are the two halves of a trigger: entering water, standing on a pressure plate, holding a capture point. Nothing fires while you stay inside — the state lives in JS between the two events, and that is deliberate, since a per-frame "stay" would be bridge traffic every frame.
550
-
551
- ```javascript
552
- const pool = Game.createSprite({
553
- x: W * 0.32, y: H * 0.3, width: W * 0.44, height: H * 0.18,
554
- sheet: waterSheet, tintColor: '#3d6fd4', opacity: 0.35,
555
- touchEnabled: false, // drags pass through to whatever is inside
556
- collisionGroup: 'water'
557
- });
558
-
559
- hero.collidesWith = ['water'];
560
- hero.addEventListener('collision', (e) => {
561
- if (e.group === 'water') {
562
- hero.tintColor = '#7fb2ff';
563
- swimming = true;
564
- }
565
- });
566
- hero.addEventListener('collisionend', (e) => {
567
- if (e.group === 'water') {
568
- hero.tintColor = null;
569
- swimming = false;
570
- }
571
- });
572
- ```
573
-
574
- The listener goes on the sprite that declares `collidesWith`. For a pressure plate holding a door open exactly while a crate rests on it, that is the **plate** (`collidesWith: ['crate']`), not the crate — then `collision` opens the door and `collisionend` closes it, with no polling anywhere.
575
-
576
- Removing the partner from the scene, hiding it (`visible = false`) or changing its `collisionGroup` mid-contact all count as separation, so the exit still fires and the door cannot stick open when an object despawns.
577
-
578
- ### Patrol routes and animation chains — `path.js`
579
-
580
- A fixed route is `followPath`, not a chain of tween legs. The points are walked natively at `speed` px/s; `rotate: true` turns the sprite to face along the path (heading `0` = up, same convention as `rotation`), and `smoothing` rounds the corners with a radius in px.
581
-
582
- ```javascript
583
- guard.followPath([
584
- { x: W * 0.22, y: H * 0.46 },
585
- { x: W * 0.78, y: H * 0.46 },
586
- { x: W * 0.78, y: H * 0.60 },
587
- { x: W * 0.22, y: H * 0.60 }
588
- ], { speed: W * 0.16, loop: true }); // sharp rectangle, walks forever
589
-
590
- ship.followPath(diamond, {
591
- speed: W * 0.35,
592
- loop: true,
593
- rotate: true, // nose follows the heading
594
- smoothing: W * 0.12 // rounds the diamond into an oval
595
- });
596
- ```
597
-
598
- A non-looping run fires `pathcomplete` and clears itself; `followPath(null)` stops in place. Two points is the minimum — one point is ignored with a warning, not treated as "go there".
599
-
600
- The path writes `x`/`y` outright, after velocity and gravity have been integrated, so **a sprite on a path ignores its own physics for placement**. It still feeds the frame delta, though, which means a platform on a looping circuit carries whatever is standing on it — a moving platform is now a path, not a tween ping-pong.
601
-
602
- Animation chains are native in the same spirit:
603
-
604
- ```javascript
605
- guard.play('hop', { then: 'walk' }); // one call, no animationcomplete handler
606
- bird.play('flap', { then: ['glide', 'idle'] });
607
- ```
608
-
609
- Each queued animation starts as the previous non-looping one finishes, and a looping animation ends the chain. `animationcomplete` still fires per step if you want to hook one. `stop()` drops the queue along with the current animation.
610
-
611
- ### Line of sight, ledge probes and hitscan — `raycast.js`
612
-
613
- `gameView.raycast(x0, y0, x1, y1, groups)` answers "what is the first thing on this line?" with `null` or `{ x, y, distance, group, sprite, normal }`. The targets need nothing but a `collisionGroup` — no `collidesWith` on the asking side.
614
-
615
- ```javascript
616
- const hit = gameView.raycast(eyeX, eyeY, dog.x, dog.y, ['blocker']);
617
- if (hit) {
618
- aimBeam(sight, eyeX, eyeY, hit.x, hit.y, hit.distance);
619
- sight.tintColor = '#f44'; // view blocked at the impact point
620
- }
621
- ```
622
-
623
- Pass the groups as an **array**. Android also accepts loose arguments, iOS does not, so the array is the portable form. Only `visible`, non-`screenFixed` sprites carrying a `collisionGroup` are candidates — a pooled sprite parked at `visible = false` is correctly invisible to the ray, an untagged wall is invisible too (the usual mistake), and HUD sprites are skipped by design so a screen-fixed score never blocks a world-space sight line.
624
-
625
- A ledge probe is the same call pointed straight down, one step ahead of the feet:
626
-
627
- ```javascript
628
- const dir = walker.velocityX >= 0 ? 1 : -1;
629
- const probeX = walker.x + dir * W * 0.07;
630
- if (!gameView.raycast(probeX, walker.y, probeX, walker.y + W * 0.12, ['ground'])) {
631
- walker.velocityX = -walker.velocityX; // nothing underfoot: turn before falling
632
- walker.flipX = walker.velocityX < 0;
633
- }
634
- ```
635
-
636
- Run these from a coarse timer or a tap handler — the demo probes at 150 ms — never once per frame. A per-frame `raycast` from JS is exactly the bridge traffic the engine is built to avoid. Note that `raycast.js` drives its probes with `setInterval`: it was written two commits before game-clock timers existed, and `gameView.every` is the better home for an AI tick today.
637
-
638
- ### Pathfinding around obstacles — `maze.js`, `pointclick.js`
639
-
640
- `gameView.findPath(from, to, options)` is grid A\* over the same sprites `raycast` sees: visible, tagged with a `collisionGroup`, nothing else to set up. It returns `{ x, y }` waypoints — or `null` — and those waypoints go straight into `followPath`, so the walk itself runs natively.
641
-
642
- ```javascript
643
- gameView.addEventListener('tap', (e) => {
644
- const path = gameView.findPath(
645
- { x: player.x, y: player.y },
646
- { x: e.x, y: e.y },
647
- { cellSize: TILE, groups: ['wall'], bounds: MAZE_BOUNDS });
648
- if (!path || path.length < 2) {
649
- return; // tapped outside the walkable rect
650
- }
651
- player.scaleX = path[1].x < player.x ? -1 : 1; // face the first leg
652
- player.play('walk');
653
- player.followPath(path, { speed: SPEED });
654
- });
655
- ```
656
-
657
- `cellSize` is the one option that decides everything else. On a tile map, pass the tile size and the grid lines up with the walls exactly; on a free-form scene, something near the walker's width. Too coarse and doorways disappear, too fine and the query gets expensive (over ~1M cells it returns `null` rather than allocating).
658
-
659
- **The path is a line for the sprite's *center*.** A body wider than a cell scrapes corners unless you pass `clearance` — about half the walker's width:
660
-
661
- ```javascript
662
- const path = gameView.findPath(from, to, {
663
- cellSize: Math.round(W * 0.04),
664
- groups: ['obstacle'],
665
- clearance: PLAYER_W * 0.35, // keep half a body off the trunk
666
- bounds: WALK_BOUNDS // the walkable floor, in center coordinates
667
- });
668
- ```
669
-
670
- `bounds` doubles as the walkable area, which is how the point-&-click floor clamp survives: `WALK_BOUNDS` is the old `WALK_TOP`/margin clamp expressed as a rect, in **sprite-center coordinates** (tap points are feet positions, so subtract half the sprite height before searching).
671
-
672
- **Obstacles do not have to be the art.** `pointclick.js` blocks only the oak's trunk with an invisible sprite — `opacity: 0`, `touchEnabled: false`, no collision wiring — because `findPath` reads the hitbox, not the pixels. The canopy stays walkable, so the player still passes behind the tree with `ySort` doing the depth:
673
-
674
- ```javascript
675
- gameView.add(Game.createSprite({
676
- sheet: treeSheet, opacity: 0, touchEnabled: false,
677
- x: tree.x, y: groundY, width: TREE_W * 0.35, height: PLAYER_H * 0.8,
678
- collisionGroup: 'obstacle'
679
- }));
680
- ```
681
-
682
- A blocked goal snaps to the nearest free cell a few rings out, so tapping a wall walks to its edge instead of doing nothing. Tapping outside `bounds` is the case worth guarding — that is what `path.length < 2` catches.
683
-
684
- **Chasing AI is a timer, not a frame loop.** Re-path on a coarse game-clock tick and let `followPath` cover the gap:
685
-
686
- ```javascript
687
- const chase = gameView.every(800, () => {
688
- const path = gameView.findPath({ x: hound.x, y: hound.y }, { x: player.x, y: player.y }, PATH_OPTIONS);
689
- if (path && path.length > 1) {
690
- hound.followPath(path, { speed: TILE * 2.6 });
691
- }
692
- });
693
- win.addEventListener('close', () => gameView.cancelTimer(chase));
694
- ```
695
-
696
- `followPath(null)` cancels an in-flight route — `maze.js` uses it to yank the hound back to its den after it catches you.
697
-
698
- To *see* what A\* did, ask twice: `simplify: false` returns every grid cell it walked, `simplify: true` (the default) the line-of-sight-reduced corners the sprite actually gets. Dropping a dot on each is the whole route visualization in the maze demo.
699
-
700
- ### Timers on the game clock
701
-
702
- `gameView.after(ms, cb)` and `every(ms, cb)` run on the engine's clock: they stretch under `timeScale` slow motion, freeze at `0`, and pause with the render loop. Spawn waves, AI decision ticks and respawn delays belong here — a paused game that keeps spawning is the bug this fixes.
703
-
704
- ```javascript
705
- const wave = gameView.every(2000, () => spawnEnemy());
706
- gameView.after(500, () => player.play('idle'));
707
- gameView.cancelTimer(wave); // both return an int id
708
- ```
709
-
710
- The callback receives `{ id }`. Called without a callback, the view fires a `timer` event carrying the same id instead — pick one, not both. A repeating timer fires at most once per frame and restarts its interval after a stall rather than bursting to catch up.
711
-
712
- What still belongs in `setTimeout`: anything that must keep running while the game is frozen. A pause menu counting down in real seconds is not on the game clock.
713
-
714
- ### Hit-stop on impact
715
-
716
- Freezing the scene for a few frames makes an impact read before the explosion starts. `timeScale = 0` stops the engine from advancing while it keeps drawing and accepting touches — no render loop to restart, no state to save. (Pattern from Titanium Lander: 140 ms on a crash, 90 ms when a shield absorbs a hit.)
717
-
718
- ```javascript
719
- let hitStopTimer = null;
720
-
721
- function hitStop(ms) {
722
- clearHitStop();
723
- gameView.timeScale = 0;
724
- hitStopTimer = setTimeout(() => {
725
- hitStopTimer = null;
726
- gameView.timeScale = 1;
727
- }, ms);
728
- }
729
-
730
- function clearHitStop() {
731
- if (hitStopTimer !== null) {
732
- clearTimeout(hitStopTimer);
733
- hitStopTimer = null;
734
- }
735
- gameView.timeScale = 1;
736
- }
737
- ```
738
-
739
- Restoring the scale must be unconditional: run `clearHitStop()` from reset, from window close and from every teardown path, because a freeze that outlives a retry starts the next round stopped.
740
-
741
- ## Tap-to-flap
742
-
743
- Gravity plus an impulse per tap. Scoring and death are collisions with invisible zones. The rotation tween is what sells the arc.
744
-
745
- ```javascript
746
- const pig = Game.createSprite({
747
- sheet: pigSheet,
748
- x: W * 0.28,
749
- y: H * 0.42,
750
- width: PIG_SIZE,
751
- height: PIG_SIZE,
752
- zIndex: 10,
753
- hitboxScale: 0.7, // the art does not fill the frame
754
- hitboxScaleY: 0.85, // ...and the pig is wider than he is tall
755
- collidesWith: ['pipe', 'ground', 'score', 'ceiling'],
756
- animations: { fly: { frames: [0, 1, 2, 1], fps: 10, loop: true } }
757
- });
758
- pig.play('fly');
759
-
760
- gameView.addEventListener('press', () => {
761
- if (over) {
762
- reset();
763
- return;
764
- }
765
- if (!started) {
766
- start(); // first tap turns gravity on
767
- }
768
- pig.velocityY = FLAP; // e.g. -H * 0.6
769
- pig.clearTweens();
770
- pig.rotation = -15; // snap the nose up...
771
- pig.animate({ rotation: 25, duration: 900, easing: Game.EASE_IN }); // ...then tip forward
772
- });
773
-
774
- pig.addEventListener('collision', (e) => {
775
- if (over) {
776
- return;
777
- }
778
- if (e.group === 'score') {
779
- score++;
780
- } else if (e.group === 'ceiling') {
781
- pig.velocityY = H * 0.1; // gentle push back down instead of a hard stop
782
- } else {
783
- gameOver();
784
- }
785
- });
786
- ```
787
-
788
- Obstacles are pooled gates: three sprites each (top pipe, bottom pipe, invisible score zone) that scroll left on `velocityX` and get repositioned when they leave the screen. Freezing the game means setting every scroller's `velocityX = 0` and the player's `gravity = 0` — the engine has no global "stop", but `gameView.timeScale = 0` is one if you want the scene frozen mid-flight.
789
-
790
- ## Platformer
791
-
792
- `solidWith` handles the blocking; you only decide when to jump.
793
-
794
- ```javascript
795
- const player = Game.createSprite({
796
- sheet: playerSheet,
797
- x: W * 0.15,
798
- y: groundTop - PLAYER_SIZE / 2,
799
- width: PLAYER_SIZE,
800
- height: PLAYER_SIZE,
801
- zIndex: 10,
802
- gravity: GRAVITY, // H * 2.2
803
- hitboxScale: 0.85,
804
- hitboxScaleX: 0.66, // the blob is 38px wide in a 64px frame, but nearly full height
805
- solidWith: ['solid', 'trampoline'],
806
- animations: {
807
- idle: { frames: [0], fps: 1, loop: true },
808
- walk: { frames: [1, 2], fps: 8, loop: true }
809
- }
810
- });
811
-
812
- gameView.follow(player, { topMargin: 0.33, bottomMargin: 0.7, maxY: 0 });
813
-
814
- let moveDir = 0;
815
-
816
- function applyMovement() {
817
- player.velocityX = moveDir * RUN_SPEED;
818
- if (moveDir !== 0) {
819
- player.scaleX = moveDir; // face the running direction
820
- }
821
- if (player.onGround) {
822
- player.play(moveDir !== 0 ? 'walk' : 'idle');
823
- }
824
- }
825
-
826
- function jump() {
827
- if (player.onGround) { // gate on the engine's own flag
828
- player.velocityY = -JUMP; // H * 0.95 ≈ 0.2 * H of height
829
- player.stop();
830
- player.frame = 3; // hold the jump pose
831
- }
832
- }
833
-
834
- player.addEventListener('land', (e) => {
835
- if (e.group === 'trampoline') {
836
- player.velocityY = -JUMP * 1.1; // bounce higher than a jump
837
- player.stop();
838
- player.frame = 3;
839
- e.other.frame = 1; // squash the mat you landed on
840
- setTimeout(() => {
841
- e.other.frame = 0;
842
- }, 150);
843
- return;
844
- }
845
- applyMovement(); // back from the jump pose
846
- });
847
- ```
848
-
849
- Jump height is `JUMP² / (2 × GRAVITY)`. Space your platforms comfortably below it — the demo uses steps of `0.14 * H` against a `0.2 * H` jump.
850
-
851
- **One-way platforms**: `oneWay: true` on the solid lets riders jump up through it and land on top, never blocking sideways or from below. This is what makes a staircase climbable.
852
-
853
- **Moving platforms carry riders for free** — a solid moved by `velocityX` or a tween drags whoever stands on it, with no re-landing jitter:
854
-
855
- ```javascript
856
- const mover = Game.createSprite({
857
- sheet: moverSheet, x: W * 0.18, y: groundTop - STEP * 2,
858
- width: W * 0.26, height: PLAT_H, collisionGroup: 'solid'
859
- });
860
-
861
- function patrol() {
862
- mover.animate({
863
- x: (mover.x < W * 0.35) ? W * 0.5 : W * 0.18,
864
- duration: 2600,
865
- easing: Game.EASE_IN_OUT
866
- });
867
- }
868
- mover.addEventListener('complete', patrol); // ping-pong forever
869
- patrol();
870
- ```
871
-
872
- Set `carryRiders: false` on terrain that scrolls under a player who should stay put (endless runners).
873
-
874
- ## Top-down / Zelda
875
-
876
- A tile map from a string array, plus `ySort` for depth. Only water is solid; trees are pure decoration you can walk behind.
877
-
878
- ```javascript
879
- const MAP = [
880
- 'WWWWWWWWWWWW',
881
- 'WGGGGGGGGGGW',
882
- 'WGGFGGGPGGGW',
883
- 'WWWWWWWWWWWW'
884
- ];
885
- const FRAMES = { G: 0, F: 1, P: 2, W: 3 };
886
- const COLS = MAP[0].length;
887
- const ROWS = MAP.length;
888
- const TILE = Math.floor(Math.min(W / COLS, (H - buttonZone) / ROWS));
889
- const ox = (W - COLS * TILE) / 2;
890
- const oy = (H - buttonZone - ROWS * TILE) / 2;
891
-
892
- const level = [];
893
- for (let row = 0; row < ROWS; row++) {
894
- for (let col = 0; col < COLS; col++) {
895
- const kind = MAP[row].charAt(col);
896
- level.push(Game.createSprite({
897
- sheet: tileSheet,
898
- frame: FRAMES[kind],
899
- x: ox + (col + 0.5) * TILE,
900
- y: oy + (row + 0.5) * TILE,
901
- width: TILE,
902
- height: TILE,
903
- zIndex: 0,
904
- collisionGroup: (kind === 'W') ? 'solid' : null // only water blocks
905
- }));
906
- }
907
- }
908
- gameView.add(level); // one bridge crossing
909
- ```
910
-
911
- This is fine at 12×15 tiles and dead at 200×200 — one sprite per tile. A native tilemap layer is on the roadmap; until then, build large worlds from a few big `tileRepeat` sprites plus sparse solids.
912
-
913
- Depth sorting: give the player, trees and buildings the **same `zIndex`** with `ySort: true`, and keep ground tiles on a lower `zIndex`. The engine then orders them by bottom edge.
914
-
915
- ```javascript
916
- const player = Game.createSprite({
917
- sheet: walkerSheet,
918
- x: start.x, y: start.y, width: TILE, height: TILE,
919
- zIndex: 5,
920
- ySort: true,
921
- hitboxScale: 0.6, // top-down games feel best with a small body box
922
- solidWith: ['solid'],
923
- animations: {
924
- down: { frames: [0, 1], fps: 6, loop: true },
925
- up: { frames: [2, 3], fps: 6, loop: true },
926
- side: { frames: [4, 5], fps: 6, loop: true }
927
- }
928
- });
929
- ```
930
-
931
- 8-way movement from four buttons, tracking facing yourself because `animation` keeps its value after `stop()`:
932
-
933
- ```javascript
934
- let moveX = 0;
935
- let moveY = 0;
936
- let lastFacing = 'down';
937
- let walking = false;
938
-
939
- function applyMovement() {
940
- player.velocityX = moveX * SPEED;
941
- player.velocityY = moveY * SPEED;
942
- if (moveX === 0 && moveY === 0) {
943
- player.stop();
944
- walking = false;
945
- player.frame = { down: 0, up: 2, side: 4 }[lastFacing];
946
- return;
947
- }
948
- const facing = (moveX !== 0) ? 'side' : (moveY < 0 ? 'up' : 'down');
949
- if (moveX !== 0) {
950
- player.scaleX = moveX; // side frames face right; mirror for left
951
- }
952
- if (!walking || facing !== lastFacing) {
953
- player.play(facing);
954
- walking = true;
955
- }
956
- lastFacing = facing;
957
- }
958
- ```
959
-
960
- **NPC on a decision timer.** The AI thinks every 100 ms; the walking itself is native velocity between ticks. This is the sanctioned use of a timer — decisions, not motion.
961
-
962
- ```javascript
963
- timer = setInterval(() => {
964
- const dx = player.x - dog.x;
965
- const dy = player.y - dog.y;
966
- const dist = Math.sqrt(dx * dx + dy * dy);
967
- if (dist > FOLLOW_DISTANCE) {
968
- dog.velocityX = (dx / dist) * DOG_SPEED;
969
- dog.velocityY = (dy / dist) * DOG_SPEED;
970
- if (Math.abs(dx) > 2) {
971
- dog.scaleX = (dx > 0) ? 1 : -1;
972
- }
973
- setDogState('walk');
974
- } else {
975
- dog.velocityX = 0;
976
- dog.velocityY = 0;
977
- setDogState('sit');
978
- }
979
- }, 100);
980
- ```
981
-
982
- ## Top-down racer
983
-
984
- `carMode` gives you throttle, steering and emergent drift. You supply the track and the lap logic.
985
-
986
- ```javascript
987
- const car = Game.createSprite({
988
- sheet: carSheet,
989
- x: W * 0.38,
990
- y: laneY,
991
- width: CAR_SIZE,
992
- height: CAR_SIZE,
993
- pixelSnap: true, // stable texel phase for pixel art in motion
994
- rotation: 90, // facing right along the bottom straight
995
- zIndex: 10,
996
- hitboxScale: 0.75,
997
- carMode: true,
998
- enginePower: MAX_SPEED * 1.1,
999
- maxSpeed: MAX_SPEED,
1000
- turnRate: 210,
1001
- grip: 3.2, // below the default 4 → drifts in fast corners
1002
- drag: 0.8,
1003
- skidMarks: true,
1004
- restitution: 0.3, // bump off the barriers instead of sticking
1005
- solidWith: ['wall'],
1006
- collidesWith: ['checkpoint', 'goal']
1007
- });
1008
- ```
1009
-
1010
- Controls write `throttle` and `steering` once per touch — never per frame:
1011
-
1012
- ```javascript
1013
- bindHold(gasButton, () => {
1014
- car.throttle = 1;
1015
- }, () => {
1016
- if (car.throttle === 1) {
1017
- car.throttle = 0;
1018
- }
1019
- });
1020
- bindHold(brakeButton, () => {
1021
- car.throttle = -1;
1022
- }, () => {
1023
- if (car.throttle === -1) {
1024
- car.throttle = 0;
1025
- }
1026
- });
1027
- ```
1028
-
1029
- Track and laps: the visible track is one sprite; the collision geometry is invisible rectangles (outer border, inner island). Checkpoints are strips across each lane, and the goal only counts a lap once all of them were visited — that is what stops a player from reversing over the finish line.
1030
-
1031
- ```javascript
1032
- car.addEventListener('collision', (e) => {
1033
- if (e.group === 'checkpoint') {
1034
- visited[e.other.cpIndex] = true;
1035
- } else if (e.group === 'goal' && Object.keys(visited).length === 3) {
1036
- laps++;
1037
- visited = {};
1038
- }
1039
- });
1040
- ```
1041
-
1042
- Tuning: lower `grip` = more drift; `turnRate` is degrees per second at full steering and full speed; `drag` decides how fast the car coasts to a stop. Read-only `drifting` is the hook for a tire-squeal sound.
1043
-
1044
- ## Asteroids / space shooter
1045
-
1046
- Newtonian flight: `thrust` accelerates along the heading, `angularVelocity` turns, `wrapAround` re-enters from the opposite edge, momentum does the rest.
1047
-
1048
- ```javascript
1049
- const ship = Game.createSprite({
1050
- sheet: shipSheet,
1051
- x: W / 2, y: H / 2, width: SHIP_SIZE, height: SHIP_SIZE,
1052
- zIndex: 10,
1053
- maxSpeed: MAX_SPEED,
1054
- wrapAround: true,
1055
- hitboxScale: 0.6,
1056
- hitboxShape: 'circle',
1057
- collidesWith: ['asteroid'],
1058
- animations: { thrust: { frames: [1, 2], fps: 14, loop: true } } // flickering flame
1059
- });
1060
-
1061
- bindHold(thrustButton, () => {
1062
- ship.thrust = THRUST; // px/s² along the heading
1063
- ship.play('thrust');
1064
- thrustSound.play(); // created with loop: true
1065
- }, () => {
1066
- ship.thrust = 0;
1067
- ship.stop();
1068
- ship.frame = 0;
1069
- thrustSound.stop();
1070
- });
1071
-
1072
- bindHold(leftButton, () => {
1073
- ship.angularVelocity = -TURN_SPEED;
1074
- }, () => {
1075
- if (ship.angularVelocity < 0) {
1076
- ship.angularVelocity = 0;
1077
- }
1078
- });
1079
- ```
1080
-
1081
- Firing from the nose, inheriting the ship's momentum — with `rotation` in degrees clockwise and y pointing down, the heading vector is `(sin θ, -cos θ)`:
1082
-
1083
- ```javascript
1084
- const rad = ship.rotation * Math.PI / 180;
1085
- const dirX = Math.sin(rad);
1086
- const dirY = -Math.cos(rad);
1087
- bullet.x = ship.x + dirX * SHIP_SIZE * 0.55;
1088
- bullet.y = ship.y + dirY * SHIP_SIZE * 0.55;
1089
- bullet.rotation = ship.rotation;
1090
- bullet.velocityX = ship.velocityX + dirX * BULLET_SPEED;
1091
- bullet.velocityY = ship.velocityY + dirY * BULLET_SPEED;
1092
- bullet.visible = true;
1093
- ```
1094
-
1095
- Give bolts `blend: 'add'` so they glow over the starfield. Autofire is a `setInterval` on the fire button — a cadence decision, not motion.
1096
-
1097
- Damage feedback and invulnerability:
1098
-
1099
- ```javascript
1100
- let invulnerableUntil = 0;
1101
-
1102
- ship.addEventListener('collision', (e) => {
1103
- if (e.group !== 'asteroid' || Date.now() < invulnerableUntil) {
1104
- return;
1105
- }
1106
- lives--;
1107
- explodeSound.play();
1108
- ship.flash('#ff5252', 400); // native red damage flash
1109
- invulnerableUntil = Date.now() + 1500;
1110
- });
1111
-
1112
- // last-life warning: one JS timer, the fade itself runs in the engine
1113
- warnTimer = setInterval(() => {
1114
- ship.flash('#ff5252', 350);
1115
- }, 700);
1116
- ```
1117
-
1118
- Rocks are round (`hitboxShape: 'circle'`), drift on random velocities, spin on `angularVelocity`, and are recycled by `visible = false` rather than removed.
1119
-
1120
- ## Lunar lander
1121
-
1122
- Same flight model as Asteroids, with gravity on and a landing test. There is no "landing" event — you judge the touchdown yourself in the `land` handler, where velocities are still readable.
1123
-
1124
- ```javascript
1125
- const lander = Game.createSprite({
1126
- sheet: shipSheet,
1127
- x: W / 2, y: H * 0.2, width: SHIP, height: SHIP,
1128
- zIndex: 10,
1129
- gravity: world.gravity, // per-world, e.g. H * 0.35 for the Moon
1130
- maxSpeed: MAX_SPEED,
1131
- hitboxScale: 0.8,
1132
- solidWith: ['terrain', 'pad'],
1133
- collidesWith: ['hazard']
1134
- });
1135
-
1136
- const MAX_LANDING_SPEED = H * 0.18;
1137
- const MAX_LANDING_TILT = 12; // degrees
1138
-
1139
- lander.addEventListener('land', (e) => {
1140
- const speed = Math.abs(lander.velocityY);
1141
- const tilt = Math.abs(((lander.rotation % 360) + 540) % 360 - 180);
1142
- const onPad = e.group === 'pad';
1143
-
1144
- if (onPad && speed <= MAX_LANDING_SPEED && tilt <= MAX_LANDING_TILT) {
1145
- succeed();
1146
- return;
1147
- }
1148
- crash();
1149
- });
1150
-
1151
- function crash() {
1152
- hitStop(140); // see the hit-stop pattern
1153
- lander.flash('#ff5252', 400);
1154
- explosion.x = lander.x;
1155
- explosion.y = lander.y;
1156
- explosion.emit(30);
1157
- gameView.shake({ strength: SHIP * 0.5, duration: 450 });
1158
- crashSound.play();
1159
- }
1160
- ```
1161
-
1162
- Thrust burns fuel on the same coarse tick that reads the controls — 80 ms is fast enough to feel responsive and slow enough to stay off the bridge:
1163
-
1164
- ```javascript
1165
- timer = setInterval(() => {
1166
- if (mainThrusterHeld && fuel > 0) {
1167
- fuel -= BURN_RATE;
1168
- lander.thrust = THRUST;
1169
- exhaust.emitting = true;
1170
- } else {
1171
- lander.thrust = 0;
1172
- exhaust.emitting = false;
1173
- }
1174
- fuelLabel.text = Math.max(0, Math.round(fuel)) + '%';
1175
- }, 80);
1176
- ```
1177
-
1178
- Wind is just a horizontal acceleration you re-apply on that same tick by nudging `velocityX`; per-world gravity, drag and wind are plain numbers in a catalog object.
1179
-
1180
- ## Endless runner
1181
-
1182
- The player never moves horizontally. Gravity plus an invisible ground solid handle the jump arc; the world scrolls past at the same speed as the obstacles, so they look glued to the street.
1183
-
1184
- ```javascript
1185
- const player = Game.createSprite({
1186
- sheet: skaterSheet,
1187
- x: W * 0.24,
1188
- y: groundTop - PLAYER / 2,
1189
- width: PLAYER, height: PLAYER,
1190
- zIndex: 10,
1191
- gravity: GRAVITY,
1192
- hitboxScale: 0.9,
1193
- solidWith: ['ground', 'platform'],
1194
- collidesWith: ['wall', 'pit'],
1195
- animations: { roll: { frames: [0, 1], fps: 6, loop: true } }
1196
- });
1197
-
1198
- function jump() {
1199
- if (!over && player.onGround) {
1200
- jumpSound.play();
1201
- dust.emitting = false; // no dust while airborne
1202
- player.velocityY = -JUMP;
1203
- player.stop();
1204
- player.frame = 2; // tuck pose
1205
- }
1206
- }
1207
-
1208
- player.addEventListener('land', () => {
1209
- if (!over) {
1210
- player.play('roll');
1211
- dust.emitting = true;
1212
- }
1213
- });
1214
- ```
1215
-
1216
- Spawning is a self-rescheduling timeout, so the gap can vary and a long obstacle can push the next spawn further out:
1217
-
1218
- ```javascript
1219
- function scheduleSpawn() {
1220
- spawnTimer = setTimeout(() => {
1221
- spawnObstacle();
1222
- scheduleSpawn();
1223
- }, 1100 + Math.random() * 800 + extraDelay);
1224
- }
1225
- ```
1226
-
1227
- Raised road sections are solids the player jumps onto, with `carryRiders: false` (the road scrolls, the skater must not be dragged with it) plus an invisible trigger on the front face so rolling into the step is a crash rather than the solid shoving the player off screen.
1228
-
1229
- Crash sequence: stop the timers, zero gravity, freeze every scroller, switch to the wipeout frame, fire a spark burst, shake the camera.
1230
-
1231
- ```javascript
1232
- function crash(group) {
1233
- over = true;
1234
- music.stop();
1235
- crashSound.play();
1236
- clearTimers();
1237
- player.gravity = 0;
1238
- player.velocityY = 0;
1239
- player.stop();
1240
- player.frame = 3;
1241
- layers.forEach((layer) => layer.setSpeed(0));
1242
- setObstacleSpeed(0);
1243
- dust.emitting = false;
1244
- sparks.x = player.x;
1245
- sparks.y = player.y;
1246
- sparks.emit(26);
1247
- gameView.shake({ strength: PLAYER * 0.12, duration: 450 });
1248
- }
1249
- ```
1250
-
1251
- ## Rhythm game
1252
-
1253
- Notes fall on native velocity; JS only handles presses and a spawn timer. Pads use `press`, not `tap` — a rhythm game cannot wait for the finger to lift.
1254
-
1255
- ```javascript
1256
- const pads = LANES.map((x, lane) => {
1257
- const pad = Game.createSprite({ sheet: padSheet, x: x, y: PAD_Y, width: PAD, height: PAD, zIndex: 5 });
1258
- pad.addEventListener('press', () => hitLane(lane, pad));
1259
- gameView.add(pad);
1260
- return pad;
1261
- });
1262
-
1263
- // gems must not swallow pad presses
1264
- const sprite = Game.createSprite({
1265
- sheet: noteSheet, width: NOTE, height: NOTE, zIndex: 10,
1266
- visible: false,
1267
- touchEnabled: false,
1268
- collidesWith: ['misszone']
1269
- });
1270
-
1271
- function hitLane(lane, pad) {
1272
- pad.frame = 1;
1273
- setTimeout(() => {
1274
- pad.frame = 0;
1275
- }, 120);
1276
-
1277
- let best = null;
1278
- let bestDistance = Infinity;
1279
- notes.forEach((note) => {
1280
- if (note.active && note.lane === lane) {
1281
- const distance = Math.abs(note.sprite.y - PAD_Y); // live native read
1282
- if (distance < bestDistance) {
1283
- bestDistance = distance;
1284
- best = note;
1285
- }
1286
- }
1287
- });
1288
-
1289
- if (best !== null && bestDistance <= HIT_RANGE) {
1290
- recycle(best);
1291
- goodSound.play();
1292
- burst.x = LANES[lane];
1293
- burst.y = PAD_Y;
1294
- burst.tint = LANE_TINTS[lane];
1295
- burst.emit(18);
1296
- score += (bestDistance <= PERFECT) ? 3 : 1;
1297
- } else {
1298
- badSound.play();
1299
- }
1300
- }
1301
- ```
1302
-
1303
- An invisible `misszone` trigger below the pads catches gems that got away and counts the miss. Derive the fall speed from the beat: `FALL_SPEED = (PAD_Y + NOTE) / 1.6` with a 400 ms spawn interval puts four eighth notes between spawn and pad at 150 BPM.
1304
-
1305
- ## Ball sports / breakout physics
1306
-
1307
- `restitution` on a circle-hitbox ball gives real reflection off walls and obstacles. Player contact is handled in JS so you control the feel.
1308
-
1309
- ```javascript
1310
- const ball = Game.createSprite({
1311
- sheet: ballSheet,
1312
- x: W / 2, y: H * 0.3, width: BALL_SIZE, height: BALL_SIZE,
1313
- zIndex: 12,
1314
- hitboxScale: 0.9,
1315
- hitboxShape: 'circle', // bounces off the net's corner along the normal
1316
- restitution: 0.75,
1317
- solidWith: ['wall', 'net'], // blocked and bounced by these
1318
- collidesWith: ['player', 'floor'] // only reported for these
1319
- });
1320
-
1321
- ball.addEventListener('collision', (e) => {
1322
- if (e.group === 'player') {
1323
- // reflect away from the blob's center, biased upward
1324
- const blob = e.other;
1325
- const dx = ball.x - blob.x;
1326
- const dy = ball.y - blob.y;
1327
- const len = Math.sqrt(dx * dx + dy * dy) || 1;
1328
- ball.velocityX = (dx / len) * HIT_SPEED;
1329
- ball.velocityY = Math.min((dy / len) * HIT_SPEED, -HIT_SPEED * 0.45);
1330
- } else if (e.group === 'floor') {
1331
- roundOver(ball.x > W / 2);
1332
- }
1333
- });
1334
- ```
1335
-
1336
- Note the split: walls and the net are `solidWith` (the engine bounces the ball off them for free), while the players and the floor are `collidesWith` (you decide what happens). For breakout, bricks go in `collidesWith` and are removed with `visible = false` on hit while the paddle and walls stay solid.
1337
-
1338
- A `restitution: 1` ball on an invisible floor bounces forever with no JS at all — and since 2026-08-27 the bounce can live on the *floor* instead, which is what makes one springy platform in an otherwise dead level a one-property change. Round obstacles, bumpers that knock each other around and a table that brings everything to rest are all in [Shaped solids](#shaped-solids-ramps-round-posts-and-bodies-that-push-back--slopesjs-circlesjs-pooljs-drumjs).
1339
-
1340
- **Opponent AI** on an 80 ms timer, reading a handful of live properties per tick:
1341
-
1342
- ```javascript
1343
- timer = setInterval(() => {
1344
- const onCpuSide = ball.x > W / 2;
1345
- const target = (running && onCpuSide) ? ball.x + PLAYER_SIZE * 0.2 : cpuHomeX;
1346
- const dx = target - cpu.x;
1347
- cpu.velocityX = (Math.abs(dx) > PLAYER_SIZE * 0.15) ? (dx > 0 ? RUN_SPEED : -RUN_SPEED) : 0;
1348
- if (running && onCpuSide && cpu.onGround
1349
- && Math.abs(ball.x - cpu.x) < PLAYER_SIZE * 1.2
1350
- && ball.y < cpu.y && ball.velocityY > 0) {
1351
- cpu.velocityY = -JUMP;
1352
- }
1353
- }, 80);
1354
- ```
1355
-
1356
- ## Cards and board games
1357
-
1358
- No physics at all — sprite taps, native tweens, glow and idle wobble.
1359
-
1360
- **Dealing** staggers one tween per card with `delay`, and flips the art on arrival:
1361
-
1362
- ```javascript
1363
- cards.forEach((card, index) => {
1364
- card.state = 'dealing';
1365
- card.sprite.idleAnimation = false; // still cards land exactly on target
1366
- card.sprite.frame = BACK_FRAME;
1367
- card.sprite.x = DECK_X;
1368
- card.sprite.y = DECK_Y;
1369
- card.sprite.zIndex = 30 + index; // above the deck while flying
1370
- card.sprite.animate({
1371
- x: card.home.x,
1372
- y: card.home.y,
1373
- rotation: card.home.rotation,
1374
- duration: 380,
1375
- delay: index * 140, // one card after another
1376
- easing: Game.EASE_IN_OUT
1377
- });
1378
- });
1379
-
1380
- sprite.addEventListener('complete', () => {
1381
- if (card.state === 'dealing') {
1382
- card.state = 'hand';
1383
- sprite.frame = card.face; // flip face up on arrival
1384
- sprite.zIndex = card.index;
1385
- sprite.idleAnimation = true; // wobble only once it has settled
1386
- }
1387
- });
1388
- ```
1389
-
1390
- **Selection** lifts the card and fades a glow in — `glowOpacity` is tweenable, so the halo appears with the movement instead of popping:
1391
-
1392
- ```javascript
1393
- sprite.addEventListener('tap', () => {
1394
- if (card.selected) {
1395
- card.selected = false;
1396
- sprite.animate({ x: home.x, y: home.y, rotation: home.rotation, scale: 1, glowOpacity: 0, duration: 150, easing: Game.EASE_OUT });
1397
- } else if (selectedCards().length < MAX_SELECTED) {
1398
- card.selected = true;
1399
- sprite.glowColor = '#ffc94d';
1400
- sprite.glowBlur = CARD_W * 0.14;
1401
- sprite.glowOpacity = 0;
1402
- sprite.animate({ y: home.y - LIFT, scale: 1.12, glowOpacity: 1, duration: 150, easing: Game.EASE_OUT });
1403
- }
1404
- });
1405
- ```
1406
-
1407
- **Drag & drop with snapping** (puzzle pieces, board tiles). The drag itself is native; you only decide where it lands:
1408
-
1409
- ```javascript
1410
- const piece = Game.createSprite({ sheet: sheet, frame: index, x: homeX, y: homeY, width: PIECE, height: PIECE, draggable: true, zIndex: 10 });
1411
-
1412
- piece.addEventListener('press', () => {
1413
- piece.zIndex = 100; // draw above everything while held
1414
- piece.animate({ scale: 1.15, duration: 120, easing: Game.EASE_OUT });
1415
- });
1416
-
1417
- piece.addEventListener('release', () => {
1418
- piece.animate({ scale: 1, duration: 120, easing: Game.EASE_OUT });
1419
- });
1420
-
1421
- piece.addEventListener('dragend', (e) => {
1422
- let best = null;
1423
- let bestDistance = SNAP_DISTANCE;
1424
- cells.forEach((cell) => {
1425
- if (cell.piece) {
1426
- return;
1427
- }
1428
- const d = Math.sqrt(Math.pow(e.x - cell.x, 2) + Math.pow(e.y - cell.y, 2));
1429
- if (d < bestDistance) {
1430
- bestDistance = d;
1431
- best = cell;
1432
- }
1433
- });
1434
- piece.zIndex = 10;
1435
- if (best) {
1436
- best.piece = piece;
1437
- piece.animate({ x: best.x, y: best.y, duration: 150, easing: Game.EASE_OUT });
1438
- } else {
1439
- piece.animate({ x: homeX, y: homeY, duration: 400, easing: Game.EASE_IN_OUT });
1440
- }
1441
- });
1442
- ```
1443
-
1444
- Because every handler is per sprite, this is multi-touch for free: each finger grabs its own piece.
1445
-
1446
- ## Point & click adventure
1447
-
1448
- Tap-to-walk routes around the scenery with `findPath` and walks the waypoints natively:
1449
-
1450
- ```javascript
1451
- const WALK_BOUNDS = { // the floor, in sprite-CENTER coordinates
1452
- minX: W * 0.06, maxX: W * 0.94,
1453
- minY: WALK_TOP - PLAYER_H / 2, maxY: H * 0.95 - PLAYER_H / 2
1454
- };
1455
-
1456
- function walkTo(x, y) {
1457
- const targetX = Math.min(Math.max(x, WALK_BOUNDS.minX), WALK_BOUNDS.maxX);
1458
- const targetY = Math.min(Math.max(y - PLAYER_H / 2, WALK_BOUNDS.minY), WALK_BOUNDS.maxY);
1459
- const path = gameView.findPath({ x: player.x, y: player.y }, { x: targetX, y: targetY }, {
1460
- cellSize: Math.round(W * 0.04),
1461
- groups: ['obstacle'],
1462
- clearance: PLAYER_W * 0.35, // keep half a body off the trunk
1463
- bounds: WALK_BOUNDS
1464
- });
1465
- if (!path || path.length < 2) {
1466
- return; // tapped outside the floor
1467
- }
1468
- player.scaleX = path[1].x < player.x ? -1 : 1; // face the first leg
1469
- player.play('walk');
1470
- player.followPath(path, { speed: WALK_SPEED }); // constant px/s, cancels the previous route
1471
- }
1472
-
1473
- player.addEventListener('pathcomplete', () => player.play('idle'));
1474
- ```
1475
-
1476
- The walkable floor is still a clamp, not geometry — but it is now expressed as the `bounds` rect the search runs in. Obstacles are separate: `pointclick.js` adds an invisible box over the oak's *trunk* only (`opacity: 0`, `touchEnabled: false`, `collisionGroup: 'obstacle'`), so the player circles the trunk and still walks behind the canopy with `ySort`. See [Pathfinding around obstacles](#pathfinding-around-obstacles--mazejs-pointclickjs) for the options.
1477
-
1478
- With nothing in the scene to route around, `findPath` returns `[start, goal]` and `followPath` walks the straight line — the same result as the distance-sized `animate()` tween this demo used before, with one less speed calculation to get wrong.
1479
-
1480
- **Hotspots and the tap conflict.** The GameView fires `tap` for *every* touch, including ones a sprite already handled, so a naive walk handler also walks when you click the bird. Hit-test the interactive sprites in JS and bail out:
1481
-
1482
- ```javascript
1483
- function over(sprite, x, y) {
1484
- return sprite.visible !== false
1485
- && Math.abs(x - sprite.x) <= sprite.width / 2 + PAD
1486
- && Math.abs(y - sprite.y) <= sprite.height / 2 + PAD;
1487
- }
1488
-
1489
- gameView.addEventListener('tap', (e) => {
1490
- if (over(bird, e.x, e.y) || over(handIcon, e.x, e.y) || over(talkIcon, e.x, e.y)) {
1491
- return;
1492
- }
1493
- hideIcons();
1494
- walkTo(e.x, e.y);
1495
- });
1496
- ```
1497
-
1498
- A verb coin is two icon sprites with `visible` toggled and `idleAnimation: true` for a bit of life while open.
1499
-
1500
- ## Particles
1501
-
1502
- Three modes, all native. Tint white art at runtime so one 16×16 texture covers every effect in the game.
1503
-
1504
- **Continuous fountain**:
1505
-
1506
- ```javascript
1507
- const fountain = Game.createEmitter({
1508
- sheet: sparkSheet, frame: 1,
1509
- x: W / 2, y: H - UNIT * 0.05,
1510
- rate: 90,
1511
- lifetime: 1600,
1512
- speed: H * 0.75, // launch up...
1513
- angle: 0, // 0 = up, clockwise degrees
1514
- spread: 25,
1515
- gravity: H * 0.45, // ...and fall back
1516
- size: UNIT * 0.03,
1517
- startScale: 1, endScale: 0.4,
1518
- startOpacity: 1, endOpacity: 0,
1519
- tint: '#ffcc44',
1520
- maxParticles: 400
1521
- });
1522
- gameView.add(fountain);
1523
- ```
1524
-
1525
- **Burst on demand** — `rate: 0`, position it and call `emit(n)`:
1526
-
1527
- ```javascript
1528
- const firework = Game.createEmitter({
1529
- sheet: sparkSheet, frame: 1,
1530
- rate: 0,
1531
- lifetime: 900,
1532
- speed: UNIT * 0.6,
1533
- spread: 360,
1534
- gravity: H * 0.25,
1535
- startScale: 1, endScale: 0.3,
1536
- maxParticles: 500
1537
- });
1538
- gameView.add(firework);
1539
-
1540
- gameView.addEventListener('tap', (e) => {
1541
- firework.x = e.x;
1542
- firework.y = e.y;
1543
- firework.tint = COLORS[colorIndex++ % COLORS.length];
1544
- firework.emit(45);
1545
- });
1546
- ```
1547
-
1548
- **Trail following a sprite** — `target` keeps up even mid-drag, with no bridge traffic:
1549
-
1550
- ```javascript
1551
- const dust = Game.createEmitter({
1552
- sheet: sparkSheet, frame: 0,
1553
- target: player,
1554
- offsetX: -PLAYER * 0.32, // behind the rear wheels
1555
- offsetY: PLAYER * 0.42,
1556
- rate: 22,
1557
- lifetime: 450,
1558
- speed: W * 0.08,
1559
- angle: -35, // up and back
1560
- spread: 50,
1561
- startOpacity: 0.45, endOpacity: 0,
1562
- tint: '#8a8580',
1563
- zIndex: 9 // behind the player
1564
- });
1565
- gameView.add(dust);
1566
-
1567
- dust.emitting = false; // the one property JS toggles at runtime
1568
- ```
1569
-
1570
- Add `blend: 'add'` for fire, magic and sparks — overlaps bloom instead of covering.
1571
-
1572
- ## Ropes and chains
1573
-
1574
- ```javascript
1575
- // hangs from a draggable ball
1576
- const ball = Game.createSprite({ sheet: ballSheet, x: W / 2, y: H * 0.22, width: BALL, height: BALL, zIndex: 10, draggable: true, hitboxShape: 'circle' });
1577
- gameView.add(ball);
1578
-
1579
- gameView.add(Game.createRope({
1580
- sheet: ropeSheet,
1581
- segments: 14,
1582
- segmentLength: H * 0.04,
1583
- thickness: W * 0.03,
1584
- gravity: H * 1.6,
1585
- damping: 0.985,
1586
- iterations: 3,
1587
- head: ball, // pinned to the sprite — drag it and the rope follows
1588
- zIndex: 5
1589
- }));
1590
-
1591
- // fixed anchor + a weight on a tether: drag it too far and it is pulled back
1592
- gameView.add(Game.createRope({
1593
- sheet: ropeSheet,
1594
- segments: 10,
1595
- segmentLength: SEG_LEN,
1596
- gravity: H * 1.6,
1597
- x: W * 0.15, y: H * 0.1, // fixed head anchor
1598
- tail: weight,
1599
- maxLength: 10 * SEG_LEN, // wrecking balls, leashes, yo-yos
1600
- zIndex: 5
1601
- }));
1602
- ```
1603
-
1604
- With sprites on both ends plus `maxLength`, dragging either one tows the other once the rope goes taut — carts, chained crates, a grappling hook whose tip you read from `rope.endX` / `rope.endY`.
1605
-
1606
- ## Camera work
1607
-
1608
- ```javascript
1609
- gameView.follow(player, {
1610
- leftMargin: 0.4, rightMargin: 0.6, // horizontal follow is off without these
1611
- topMargin: 0.4, bottomMargin: 0.6,
1612
- smoothing: 0.12, // 0 snaps; higher eases
1613
- maxY: WORLD_H // default 0 clamps to the top of the world
1614
- });
1615
- gameView.cameraBounds = { minX: 0, minY: 0, maxX: WORLD_W, maxY: WORLD_H };
1616
- ```
1617
-
1618
- Sprites live in world coordinates and touch input is mapped back to world space automatically, zoom included — taps and drags keep working while scrolled. Overlaid Titanium controls are screen-fixed and unaffected.
1619
-
1620
- ```javascript
1621
- gameView.cameraScale = Math.min(2.5, Math.max(0.5, gameView.cameraScale * 1.25)); // zoom
1622
- gameView.shake({ strength: W * 0.02, duration: 500 }); // impact
1623
- gameView.cameraEffect = 'tint'; // night vision
1624
- gameView.cameraTint = '#4f8';
1625
- gameView.cameraEffectIntensity = 0.7;
1626
- gameView.cameraEffect = 'glitch'; // broken signal
1627
- gameView.cameraEffect = 'none'; // skips the pass entirely
1628
- ```
1629
-
1630
- For a big ground plane, one `tileRepeat` sprite covering the whole world beats a grid of tile sprites — the texture keeps its native density and the scene stays one draw call.
1631
-
1632
- ## Visual effects
1633
-
1634
- **Blend modes** — four, on sprites and emitters alike. `blend.js` shows all of them side by side over a bright meadow strip:
1635
-
1636
- | Mode | Does | Use for |
1637
- | --- | --- | --- |
1638
- | `'normal'` | Covers what is behind it | Everything else |
1639
- | `'add'` | Sums toward white | Glows, fire, lasers, light shafts, sparks |
1640
- | `'multiply'` | Darkens the backdrop | Contact shadows under sprites, stains, grime, smoke that dims |
1641
- | `'screen'` | Lightens without blowing out | Fog, haze, god rays, soft light |
1642
-
1643
- Group same-blend sprites on their own `zIndex` band: every mode change in draw order costs a batch flush, so alternating them sprite by sprite degrades toward one draw call each. Unknown strings fall back to `'normal'` in silence and the names are case-sensitive — `blend: 'Add'` renders as normal with no warning.
1644
-
1645
- **`flash(color, duration)`** — a solid-color silhouette that fades out natively. This is the damage flash a multiplicative `tintColor` cannot produce (white tint = no change). Retrigger it on a timer for invincibility blinking.
1646
-
1647
- **`flipX` / `flipY` from movement** — mirror the drawn frame without touching physics:
1648
-
1649
- ```javascript
1650
- // tween patrol: flip on each turn-around
1651
- function patrol() {
1652
- const goingRight = bird.x < W / 2;
1653
- bird.flipX = !goingRight;
1654
- bird.animate({ x: goingRight ? W - MARGIN : MARGIN, duration: 3000, easing: Game.EASE_IN_OUT });
1655
- }
1656
- bird.addEventListener('complete', patrol);
1657
-
1658
- // velocity runner: a slow watchdog turns it around, never moves it
1659
- timer = setInterval(() => {
1660
- [dog, player].forEach((runner) => {
1661
- if (runner.velocityX > 0 && runner.x > W - MARGIN) {
1662
- runner.velocityX = -runner.velocityX;
1663
- } else if (runner.velocityX < 0 && runner.x < MARGIN) {
1664
- runner.velocityX = -runner.velocityX;
1665
- }
1666
- runner.flipX = runner.velocityX < 0;
1667
- });
1668
- }, 150);
1669
-
1670
- // VVVVVV-style gravity inversion
1671
- gameView.addEventListener('tap', () => {
1672
- player.gravity = -player.gravity;
1673
- player.flipY = player.gravity < 0;
1674
- });
1675
- ```
1676
-
1677
- **`timeScale`** — one property slows or freezes physics, sheet animations, tweens, particles, the camera and the game-clock timers together, while rendering and touch keep running. `0.5` for slow motion, `0` for a pause that still draws, short bursts of `0` for hit-stop. `timescale.js` makes the timer half visible: a clock on `gameView.every(1000, ...)` freezes with the scene while a `setInterval` clock beside it keeps ticking.
1678
-
1679
- **`idleAnimation`** — a per-sprite organic sway that composes with tweens and drags. Cheap life for cards, icons, floating pickups and menu art. Disable it before a tween that must land precisely.