@maccesar/titools 4.6.1 → 4.7.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.
@@ -0,0 +1,1220 @@
1
+ # ti.game recipes by genre
2
+
3
+ Working patterns distilled from the 18 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 0.3.0. Check [roadmap.md](roadmap.md) before reaching for anything not shown here.
6
+
7
+ ## Contents
8
+
9
+ - [The scaffolding](#the-scaffolding)
10
+ - [Cross-cutting patterns](#cross-cutting-patterns) — pooling, parallax, multitouch controls, HUD, invisible triggers, hit-stop
11
+ - [Tap-to-flap](#tap-to-flap) (`flappy.js`)
12
+ - [Platformer](#platformer) (`platformer.js`)
13
+ - [Top-down / Zelda](#top-down--zelda) (`topdown.js`)
14
+ - [Top-down racer](#top-down-racer) (`racing.js`)
15
+ - [Asteroids / space shooter](#asteroids--space-shooter) (`asteroids.js`)
16
+ - [Lunar lander](#lunar-lander)
17
+ - [Endless runner](#endless-runner) (`skate.js`)
18
+ - [Rhythm game](#rhythm-game) (`rhythm.js`)
19
+ - [Ball sports / breakout physics](#ball-sports--breakout-physics) (`volley.js`)
20
+ - [Cards and board games](#cards-and-board-games) (`cards.js`, `puzzle.js`)
21
+ - [Point & click adventure](#point--click-adventure) (`pointclick.js`)
22
+ - [Particles](#particles) (`particles.js`)
23
+ - [Ropes and chains](#ropes-and-chains) (`rope.js`)
24
+ - [Camera work](#camera-work) (`camera.js`)
25
+ - [Visual effects](#visual-effects) (`blend.js`, `flip.js`, `timescale.js`)
26
+
27
+ ## The scaffolding
28
+
29
+ Every game repeats this shape. Sheets and sounds are created once, outside `resize`, because they are texture handles, not scene objects.
30
+
31
+ ```javascript
32
+ const Game = require('ti.game');
33
+
34
+ module.exports = function () {
35
+
36
+ const win = Ti.UI.createWindow({
37
+ backgroundColor: '#000',
38
+ theme: 'Theme.Titanium.DayNight.NoTitleBar'
39
+ });
40
+ const gameView = Game.createGameView({
41
+ backgroundColor: '#8ed8f8',
42
+ maxFps: 60
43
+ // debug: true // draw every collision shape while tuning hitboxes
44
+ });
45
+
46
+ const heroSheet = Game.createSpriteSheet({ image: 'assets/hero.png', frameWidth: 64, frameHeight: 64 });
47
+ const jumpSound = Game.createSound({ url: 'assets/jump.wav', volume: 0.8 });
48
+
49
+ let timer = null;
50
+ win.addEventListener('close', () => {
51
+ if (timer !== null) {
52
+ clearInterval(timer);
53
+ timer = null;
54
+ }
55
+ });
56
+
57
+ let initialized = false;
58
+ gameView.addEventListener('resize', (e) => {
59
+ if (initialized) {
60
+ return;
61
+ }
62
+ initialized = true;
63
+ init(e.width, e.height);
64
+ });
65
+
66
+ function init(W, H) {
67
+ // The whole game lives here. Derive every size from W and H so the
68
+ // layout holds on any screen: SPEED = W * 0.35, GRAVITY = H * 2.2.
69
+ }
70
+
71
+ win.add(gameView);
72
+ win.open();
73
+ };
74
+ ```
75
+
76
+ 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`.
77
+
78
+ ## Cross-cutting patterns
79
+
80
+ ### Object pooling
81
+
82
+ Create a fixed set once, recycle forever. `visible = false` also removes the sprite from collision, which is what makes this work.
83
+
84
+ ```javascript
85
+ const bullets = [];
86
+ for (let i = 0; i < 10; i++) {
87
+ const sprite = Game.createSprite({
88
+ sheet: shipSheet,
89
+ frame: 3,
90
+ width: 8,
91
+ height: 16,
92
+ visible: false,
93
+ wrapAround: true,
94
+ hitboxScale: 1.4, // generous — bolts are small and fast
95
+ collidesWith: ['asteroid']
96
+ });
97
+ const state = { sprite: sprite, active: false, generation: 0 };
98
+
99
+ sprite.addEventListener('collision', (e) => {
100
+ if (!state.active) {
101
+ return;
102
+ }
103
+ deactivate(state);
104
+ e.other.visible = false; // the rock is gone: no render, no collision
105
+ });
106
+
107
+ gameView.add(sprite);
108
+ bullets.push(state);
109
+ }
110
+
111
+ function deactivate(state) {
112
+ state.active = false;
113
+ state.sprite.visible = false;
114
+ state.sprite.velocityX = 0;
115
+ state.sprite.velocityY = 0;
116
+ }
117
+
118
+ function fire(x, y, vx, vy) {
119
+ const state = bullets.find((b) => !b.active);
120
+ if (!state) {
121
+ return; // pool exhausted — drop the shot
122
+ }
123
+ state.active = true;
124
+ state.generation++;
125
+ const generation = state.generation;
126
+ Object.assign(state.sprite, { x: x, y: y, velocityX: vx, velocityY: vy, visible: true });
127
+ setTimeout(() => {
128
+ // burn out — unless this slot was already recycled by a newer shot
129
+ if (state.active && state.generation === generation) {
130
+ deactivate(state);
131
+ }
132
+ }, 1200);
133
+ }
134
+ ```
135
+
136
+ The `generation` counter matters: without it, a timeout fired for an old shot deactivates the *new* bullet occupying that slot.
137
+
138
+ ### Seamless parallax
139
+
140
+ 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.
141
+
142
+ ```javascript
143
+ function makeLayer(sheet, y, height, speed, z) {
144
+ const copies = [];
145
+ for (let i = 0; i < 2; i++) {
146
+ const s = Game.createSprite({
147
+ sheet: sheet,
148
+ x: W / 2 + i * W,
149
+ y: y,
150
+ width: W,
151
+ height: height,
152
+ zIndex: z,
153
+ tileRepeat: 'x', // keeps texture density; needs repeat: true on the sheet
154
+ wrapX: -W / 2,
155
+ wrapShift: 2 * W
156
+ });
157
+ gameView.add(s);
158
+ copies.push(s);
159
+ }
160
+ return {
161
+ setSpeed: (v) => copies.forEach((copy) => {
162
+ copy.velocityX = -v;
163
+ })
164
+ };
165
+ }
166
+
167
+ const skyline = makeLayer(skylineSheet, groundTop - SKY_H / 2, SKY_H, SPEED * 0.12, 1);
168
+ const street = makeLayer(streetSheet, (groundTop + H) / 2, H - groundTop, SPEED, 8);
169
+ ```
170
+
171
+ 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.
172
+
173
+ ### Multitouch on-screen controls
174
+
175
+ 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.
176
+
177
+ ```javascript
178
+ function makeButton(title, position, fontSize) {
179
+ const button = Ti.UI.createLabel({
180
+ text: title,
181
+ textAlign: 'center',
182
+ color: '#fff',
183
+ font: { fontSize: fontSize || 30, fontWeight: 'bold' },
184
+ backgroundColor: '#59000000',
185
+ borderRadius: 40,
186
+ width: '80dp',
187
+ height: '80dp',
188
+ bottom: '24dp'
189
+ });
190
+ // Manual press feedback: touchFeedback's ripple cannot animate over this
191
+ // canvas and spams RippleDrawable errors on Android.
192
+ button.addEventListener('touchstart', () => {
193
+ button.backgroundColor = '#8c000000';
194
+ });
195
+ ['touchend', 'touchcancel'].forEach((event) => {
196
+ button.addEventListener(event, () => {
197
+ button.backgroundColor = '#59000000';
198
+ });
199
+ });
200
+ Object.assign(button, position);
201
+ return button;
202
+ }
203
+
204
+ function bindHold(button, apply, release) {
205
+ button.addEventListener('touchstart', apply);
206
+ ['touchend', 'touchcancel'].forEach((event) => {
207
+ button.addEventListener(event, release);
208
+ });
209
+ }
210
+
211
+ const leftButton = makeButton('◀', { left: '24dp' });
212
+ bindHold(leftButton, () => {
213
+ car.steering = -1;
214
+ }, () => {
215
+ if (car.steering === -1) { // don't cancel the other button's input
216
+ car.steering = 0;
217
+ }
218
+ });
219
+ ```
220
+
221
+ 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.
222
+
223
+ ### HUD
224
+
225
+ There is no text in the engine. Overlay `Ti.UI.Label` views on the window, above the GameView.
226
+
227
+ ```javascript
228
+ const scoreLabel = Ti.UI.createLabel({
229
+ text: '0',
230
+ color: '#fff',
231
+ font: { fontSize: 28, fontWeight: 'bold' },
232
+ shadowColor: '#000',
233
+ shadowOffset: { x: 0, y: 2 },
234
+ top: 40
235
+ });
236
+ win.add(gameView);
237
+ win.add(scoreLabel); // added after the game view, so it draws on top
238
+ ```
239
+
240
+ The shadow is not decoration — it keeps the label readable over any background the scene happens to scroll underneath.
241
+
242
+ ### Invisible triggers
243
+
244
+ 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.
245
+
246
+ ```javascript
247
+ // score zone in the gap between two pipes
248
+ gameView.add(Game.createSprite({ x: gateX, y: gapCenter, width: 20, height: GAP, collisionGroup: 'score' }));
249
+
250
+ // invisible ceiling so the player cannot escape upward
251
+ gameView.add(Game.createSprite({ x: W / 2, y: -20, width: W * 3, height: 40, collisionGroup: 'ceiling' }));
252
+
253
+ // side walls
254
+ [-20, W + 20].forEach((x) => {
255
+ gameView.add(Game.createSprite({ x: x, y: H / 2, width: 40, height: H * 3, collisionGroup: 'wall' }));
256
+ });
257
+ ```
258
+
259
+ Attach your own metadata to a sprite and read it back from `e.other` in the handler:
260
+
261
+ ```javascript
262
+ const zone = Game.createSprite({ x: cp.x, y: cp.y, width: cp.w, height: cp.h, collisionGroup: 'checkpoint' });
263
+ zone.cpIndex = index;
264
+
265
+ car.addEventListener('collision', (e) => {
266
+ if (e.group === 'checkpoint') {
267
+ visited[e.other.cpIndex] = true;
268
+ }
269
+ });
270
+ ```
271
+
272
+ ### Hit-stop on impact
273
+
274
+ 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.)
275
+
276
+ ```javascript
277
+ let hitStopTimer = null;
278
+
279
+ function hitStop(ms) {
280
+ clearHitStop();
281
+ gameView.timeScale = 0;
282
+ hitStopTimer = setTimeout(() => {
283
+ hitStopTimer = null;
284
+ gameView.timeScale = 1;
285
+ }, ms);
286
+ }
287
+
288
+ function clearHitStop() {
289
+ if (hitStopTimer !== null) {
290
+ clearTimeout(hitStopTimer);
291
+ hitStopTimer = null;
292
+ }
293
+ gameView.timeScale = 1;
294
+ }
295
+ ```
296
+
297
+ 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.
298
+
299
+ ## Tap-to-flap
300
+
301
+ Gravity plus an impulse per tap. Scoring and death are collisions with invisible zones. The rotation tween is what sells the arc.
302
+
303
+ ```javascript
304
+ const pig = Game.createSprite({
305
+ sheet: pigSheet,
306
+ x: W * 0.28,
307
+ y: H * 0.42,
308
+ width: PIG_SIZE,
309
+ height: PIG_SIZE,
310
+ zIndex: 10,
311
+ hitboxScale: 0.7, // the art does not fill the frame
312
+ collidesWith: ['pipe', 'ground', 'score', 'ceiling'],
313
+ animations: { fly: { frames: [0, 1, 2, 1], fps: 10, loop: true } }
314
+ });
315
+ pig.play('fly');
316
+
317
+ gameView.addEventListener('press', () => {
318
+ if (over) {
319
+ reset();
320
+ return;
321
+ }
322
+ if (!started) {
323
+ start(); // first tap turns gravity on
324
+ }
325
+ pig.velocityY = FLAP; // e.g. -H * 0.6
326
+ pig.clearTweens();
327
+ pig.rotation = -15; // snap the nose up...
328
+ pig.animate({ rotation: 25, duration: 900, easing: Game.EASE_IN }); // ...then tip forward
329
+ });
330
+
331
+ pig.addEventListener('collision', (e) => {
332
+ if (over) {
333
+ return;
334
+ }
335
+ if (e.group === 'score') {
336
+ score++;
337
+ } else if (e.group === 'ceiling') {
338
+ pig.velocityY = H * 0.1; // gentle push back down instead of a hard stop
339
+ } else {
340
+ gameOver();
341
+ }
342
+ });
343
+ ```
344
+
345
+ 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.
346
+
347
+ ## Platformer
348
+
349
+ `solidWith` handles the blocking; you only decide when to jump.
350
+
351
+ ```javascript
352
+ const player = Game.createSprite({
353
+ sheet: playerSheet,
354
+ x: W * 0.15,
355
+ y: groundTop - PLAYER_SIZE / 2,
356
+ width: PLAYER_SIZE,
357
+ height: PLAYER_SIZE,
358
+ zIndex: 10,
359
+ gravity: GRAVITY, // H * 2.2
360
+ hitboxScale: 0.85,
361
+ solidWith: ['solid', 'trampoline'],
362
+ animations: {
363
+ idle: { frames: [0], fps: 1, loop: true },
364
+ walk: { frames: [1, 2], fps: 8, loop: true }
365
+ }
366
+ });
367
+
368
+ gameView.follow(player, { topMargin: 0.33, bottomMargin: 0.7, maxY: 0 });
369
+
370
+ let moveDir = 0;
371
+
372
+ function applyMovement() {
373
+ player.velocityX = moveDir * RUN_SPEED;
374
+ if (moveDir !== 0) {
375
+ player.scaleX = moveDir; // face the running direction
376
+ }
377
+ if (player.onGround) {
378
+ player.play(moveDir !== 0 ? 'walk' : 'idle');
379
+ }
380
+ }
381
+
382
+ function jump() {
383
+ if (player.onGround) { // gate on the engine's own flag
384
+ player.velocityY = -JUMP; // H * 0.95 ≈ 0.2 * H of height
385
+ player.stop();
386
+ player.frame = 3; // hold the jump pose
387
+ }
388
+ }
389
+
390
+ player.addEventListener('land', (e) => {
391
+ if (e.group === 'trampoline') {
392
+ player.velocityY = -JUMP * 1.1; // bounce higher than a jump
393
+ player.stop();
394
+ player.frame = 3;
395
+ e.other.frame = 1; // squash the mat you landed on
396
+ setTimeout(() => {
397
+ e.other.frame = 0;
398
+ }, 150);
399
+ return;
400
+ }
401
+ applyMovement(); // back from the jump pose
402
+ });
403
+ ```
404
+
405
+ 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.
406
+
407
+ **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.
408
+
409
+ **Moving platforms carry riders for free** — a solid moved by `velocityX` or a tween drags whoever stands on it, with no re-landing jitter:
410
+
411
+ ```javascript
412
+ const mover = Game.createSprite({
413
+ sheet: moverSheet, x: W * 0.18, y: groundTop - STEP * 2,
414
+ width: W * 0.26, height: PLAT_H, collisionGroup: 'solid'
415
+ });
416
+
417
+ function patrol() {
418
+ mover.animate({
419
+ x: (mover.x < W * 0.35) ? W * 0.5 : W * 0.18,
420
+ duration: 2600,
421
+ easing: Game.EASE_IN_OUT
422
+ });
423
+ }
424
+ mover.addEventListener('complete', patrol); // ping-pong forever
425
+ patrol();
426
+ ```
427
+
428
+ Set `carryRiders: false` on terrain that scrolls under a player who should stay put (endless runners).
429
+
430
+ ## Top-down / Zelda
431
+
432
+ A tile map from a string array, plus `ySort` for depth. Only water is solid; trees are pure decoration you can walk behind.
433
+
434
+ ```javascript
435
+ const MAP = [
436
+ 'WWWWWWWWWWWW',
437
+ 'WGGGGGGGGGGW',
438
+ 'WGGFGGGPGGGW',
439
+ 'WWWWWWWWWWWW'
440
+ ];
441
+ const FRAMES = { G: 0, F: 1, P: 2, W: 3 };
442
+ const COLS = MAP[0].length;
443
+ const ROWS = MAP.length;
444
+ const TILE = Math.floor(Math.min(W / COLS, (H - buttonZone) / ROWS));
445
+ const ox = (W - COLS * TILE) / 2;
446
+ const oy = (H - buttonZone - ROWS * TILE) / 2;
447
+
448
+ const level = [];
449
+ for (let row = 0; row < ROWS; row++) {
450
+ for (let col = 0; col < COLS; col++) {
451
+ const kind = MAP[row].charAt(col);
452
+ level.push(Game.createSprite({
453
+ sheet: tileSheet,
454
+ frame: FRAMES[kind],
455
+ x: ox + (col + 0.5) * TILE,
456
+ y: oy + (row + 0.5) * TILE,
457
+ width: TILE,
458
+ height: TILE,
459
+ zIndex: 0,
460
+ collisionGroup: (kind === 'W') ? 'solid' : null // only water blocks
461
+ }));
462
+ }
463
+ }
464
+ gameView.add(level); // one bridge crossing
465
+ ```
466
+
467
+ 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.
468
+
469
+ 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.
470
+
471
+ ```javascript
472
+ const player = Game.createSprite({
473
+ sheet: walkerSheet,
474
+ x: start.x, y: start.y, width: TILE, height: TILE,
475
+ zIndex: 5,
476
+ ySort: true,
477
+ hitboxScale: 0.6, // top-down games feel best with a small body box
478
+ solidWith: ['solid'],
479
+ animations: {
480
+ down: { frames: [0, 1], fps: 6, loop: true },
481
+ up: { frames: [2, 3], fps: 6, loop: true },
482
+ side: { frames: [4, 5], fps: 6, loop: true }
483
+ }
484
+ });
485
+ ```
486
+
487
+ 8-way movement from four buttons, tracking facing yourself because `animation` keeps its value after `stop()`:
488
+
489
+ ```javascript
490
+ let moveX = 0;
491
+ let moveY = 0;
492
+ let lastFacing = 'down';
493
+ let walking = false;
494
+
495
+ function applyMovement() {
496
+ player.velocityX = moveX * SPEED;
497
+ player.velocityY = moveY * SPEED;
498
+ if (moveX === 0 && moveY === 0) {
499
+ player.stop();
500
+ walking = false;
501
+ player.frame = { down: 0, up: 2, side: 4 }[lastFacing];
502
+ return;
503
+ }
504
+ const facing = (moveX !== 0) ? 'side' : (moveY < 0 ? 'up' : 'down');
505
+ if (moveX !== 0) {
506
+ player.scaleX = moveX; // side frames face right; mirror for left
507
+ }
508
+ if (!walking || facing !== lastFacing) {
509
+ player.play(facing);
510
+ walking = true;
511
+ }
512
+ lastFacing = facing;
513
+ }
514
+ ```
515
+
516
+ **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.
517
+
518
+ ```javascript
519
+ timer = setInterval(() => {
520
+ const dx = player.x - dog.x;
521
+ const dy = player.y - dog.y;
522
+ const dist = Math.sqrt(dx * dx + dy * dy);
523
+ if (dist > FOLLOW_DISTANCE) {
524
+ dog.velocityX = (dx / dist) * DOG_SPEED;
525
+ dog.velocityY = (dy / dist) * DOG_SPEED;
526
+ if (Math.abs(dx) > 2) {
527
+ dog.scaleX = (dx > 0) ? 1 : -1;
528
+ }
529
+ setDogState('walk');
530
+ } else {
531
+ dog.velocityX = 0;
532
+ dog.velocityY = 0;
533
+ setDogState('sit');
534
+ }
535
+ }, 100);
536
+ ```
537
+
538
+ ## Top-down racer
539
+
540
+ `carMode` gives you throttle, steering and emergent drift. You supply the track and the lap logic.
541
+
542
+ ```javascript
543
+ const car = Game.createSprite({
544
+ sheet: carSheet,
545
+ x: W * 0.38,
546
+ y: laneY,
547
+ width: CAR_SIZE,
548
+ height: CAR_SIZE,
549
+ pixelSnap: true, // stable texel phase for pixel art in motion
550
+ rotation: 90, // facing right along the bottom straight
551
+ zIndex: 10,
552
+ hitboxScale: 0.75,
553
+ carMode: true,
554
+ enginePower: MAX_SPEED * 1.1,
555
+ maxSpeed: MAX_SPEED,
556
+ turnRate: 210,
557
+ grip: 3.2, // below the default 4 → drifts in fast corners
558
+ drag: 0.8,
559
+ skidMarks: true,
560
+ restitution: 0.3, // bump off the barriers instead of sticking
561
+ solidWith: ['wall'],
562
+ collidesWith: ['checkpoint', 'goal']
563
+ });
564
+ ```
565
+
566
+ Controls write `throttle` and `steering` once per touch — never per frame:
567
+
568
+ ```javascript
569
+ bindHold(gasButton, () => {
570
+ car.throttle = 1;
571
+ }, () => {
572
+ if (car.throttle === 1) {
573
+ car.throttle = 0;
574
+ }
575
+ });
576
+ bindHold(brakeButton, () => {
577
+ car.throttle = -1;
578
+ }, () => {
579
+ if (car.throttle === -1) {
580
+ car.throttle = 0;
581
+ }
582
+ });
583
+ ```
584
+
585
+ 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.
586
+
587
+ ```javascript
588
+ car.addEventListener('collision', (e) => {
589
+ if (e.group === 'checkpoint') {
590
+ visited[e.other.cpIndex] = true;
591
+ } else if (e.group === 'goal' && Object.keys(visited).length === 3) {
592
+ laps++;
593
+ visited = {};
594
+ }
595
+ });
596
+ ```
597
+
598
+ 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.
599
+
600
+ ## Asteroids / space shooter
601
+
602
+ Newtonian flight: `thrust` accelerates along the heading, `angularVelocity` turns, `wrapAround` re-enters from the opposite edge, momentum does the rest.
603
+
604
+ ```javascript
605
+ const ship = Game.createSprite({
606
+ sheet: shipSheet,
607
+ x: W / 2, y: H / 2, width: SHIP_SIZE, height: SHIP_SIZE,
608
+ zIndex: 10,
609
+ maxSpeed: MAX_SPEED,
610
+ wrapAround: true,
611
+ hitboxScale: 0.6,
612
+ hitboxShape: 'circle',
613
+ collidesWith: ['asteroid'],
614
+ animations: { thrust: { frames: [1, 2], fps: 14, loop: true } } // flickering flame
615
+ });
616
+
617
+ bindHold(thrustButton, () => {
618
+ ship.thrust = THRUST; // px/s² along the heading
619
+ ship.play('thrust');
620
+ thrustSound.play(); // created with loop: true
621
+ }, () => {
622
+ ship.thrust = 0;
623
+ ship.stop();
624
+ ship.frame = 0;
625
+ thrustSound.stop();
626
+ });
627
+
628
+ bindHold(leftButton, () => {
629
+ ship.angularVelocity = -TURN_SPEED;
630
+ }, () => {
631
+ if (ship.angularVelocity < 0) {
632
+ ship.angularVelocity = 0;
633
+ }
634
+ });
635
+ ```
636
+
637
+ Firing from the nose, inheriting the ship's momentum — with `rotation` in degrees clockwise and y pointing down, the heading vector is `(sin θ, -cos θ)`:
638
+
639
+ ```javascript
640
+ const rad = ship.rotation * Math.PI / 180;
641
+ const dirX = Math.sin(rad);
642
+ const dirY = -Math.cos(rad);
643
+ bullet.x = ship.x + dirX * SHIP_SIZE * 0.55;
644
+ bullet.y = ship.y + dirY * SHIP_SIZE * 0.55;
645
+ bullet.rotation = ship.rotation;
646
+ bullet.velocityX = ship.velocityX + dirX * BULLET_SPEED;
647
+ bullet.velocityY = ship.velocityY + dirY * BULLET_SPEED;
648
+ bullet.visible = true;
649
+ ```
650
+
651
+ Give bolts `blend: 'add'` so they glow over the starfield. Autofire is a `setInterval` on the fire button — a cadence decision, not motion.
652
+
653
+ Damage feedback and invulnerability:
654
+
655
+ ```javascript
656
+ let invulnerableUntil = 0;
657
+
658
+ ship.addEventListener('collision', (e) => {
659
+ if (e.group !== 'asteroid' || Date.now() < invulnerableUntil) {
660
+ return;
661
+ }
662
+ lives--;
663
+ explodeSound.play();
664
+ ship.flash('#ff5252', 400); // native red damage flash
665
+ invulnerableUntil = Date.now() + 1500;
666
+ });
667
+
668
+ // last-life warning: one JS timer, the fade itself runs in the engine
669
+ warnTimer = setInterval(() => {
670
+ ship.flash('#ff5252', 350);
671
+ }, 700);
672
+ ```
673
+
674
+ Rocks are round (`hitboxShape: 'circle'`), drift on random velocities, spin on `angularVelocity`, and are recycled by `visible = false` rather than removed.
675
+
676
+ ## Lunar lander
677
+
678
+ 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.
679
+
680
+ ```javascript
681
+ const lander = Game.createSprite({
682
+ sheet: shipSheet,
683
+ x: W / 2, y: H * 0.2, width: SHIP, height: SHIP,
684
+ zIndex: 10,
685
+ gravity: world.gravity, // per-world, e.g. H * 0.35 for the Moon
686
+ maxSpeed: MAX_SPEED,
687
+ hitboxScale: 0.8,
688
+ solidWith: ['terrain', 'pad'],
689
+ collidesWith: ['hazard']
690
+ });
691
+
692
+ const MAX_LANDING_SPEED = H * 0.18;
693
+ const MAX_LANDING_TILT = 12; // degrees
694
+
695
+ lander.addEventListener('land', (e) => {
696
+ const speed = Math.abs(lander.velocityY);
697
+ const tilt = Math.abs(((lander.rotation % 360) + 540) % 360 - 180);
698
+ const onPad = e.group === 'pad';
699
+
700
+ if (onPad && speed <= MAX_LANDING_SPEED && tilt <= MAX_LANDING_TILT) {
701
+ succeed();
702
+ return;
703
+ }
704
+ crash();
705
+ });
706
+
707
+ function crash() {
708
+ hitStop(140); // see the hit-stop pattern
709
+ lander.flash('#ff5252', 400);
710
+ explosion.x = lander.x;
711
+ explosion.y = lander.y;
712
+ explosion.emit(30);
713
+ gameView.shake({ strength: SHIP * 0.5, duration: 450 });
714
+ crashSound.play();
715
+ }
716
+ ```
717
+
718
+ 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:
719
+
720
+ ```javascript
721
+ timer = setInterval(() => {
722
+ if (mainThrusterHeld && fuel > 0) {
723
+ fuel -= BURN_RATE;
724
+ lander.thrust = THRUST;
725
+ exhaust.emitting = true;
726
+ } else {
727
+ lander.thrust = 0;
728
+ exhaust.emitting = false;
729
+ }
730
+ fuelLabel.text = Math.max(0, Math.round(fuel)) + '%';
731
+ }, 80);
732
+ ```
733
+
734
+ 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.
735
+
736
+ ## Endless runner
737
+
738
+ 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.
739
+
740
+ ```javascript
741
+ const player = Game.createSprite({
742
+ sheet: skaterSheet,
743
+ x: W * 0.24,
744
+ y: groundTop - PLAYER / 2,
745
+ width: PLAYER, height: PLAYER,
746
+ zIndex: 10,
747
+ gravity: GRAVITY,
748
+ hitboxScale: 0.9,
749
+ solidWith: ['ground', 'platform'],
750
+ collidesWith: ['wall', 'pit'],
751
+ animations: { roll: { frames: [0, 1], fps: 6, loop: true } }
752
+ });
753
+
754
+ function jump() {
755
+ if (!over && player.onGround) {
756
+ jumpSound.play();
757
+ dust.emitting = false; // no dust while airborne
758
+ player.velocityY = -JUMP;
759
+ player.stop();
760
+ player.frame = 2; // tuck pose
761
+ }
762
+ }
763
+
764
+ player.addEventListener('land', () => {
765
+ if (!over) {
766
+ player.play('roll');
767
+ dust.emitting = true;
768
+ }
769
+ });
770
+ ```
771
+
772
+ Spawning is a self-rescheduling timeout, so the gap can vary and a long obstacle can push the next spawn further out:
773
+
774
+ ```javascript
775
+ function scheduleSpawn() {
776
+ spawnTimer = setTimeout(() => {
777
+ spawnObstacle();
778
+ scheduleSpawn();
779
+ }, 1100 + Math.random() * 800 + extraDelay);
780
+ }
781
+ ```
782
+
783
+ 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.
784
+
785
+ Crash sequence: stop the timers, zero gravity, freeze every scroller, switch to the wipeout frame, fire a spark burst, shake the camera.
786
+
787
+ ```javascript
788
+ function crash(group) {
789
+ over = true;
790
+ music.stop();
791
+ crashSound.play();
792
+ clearTimers();
793
+ player.gravity = 0;
794
+ player.velocityY = 0;
795
+ player.stop();
796
+ player.frame = 3;
797
+ layers.forEach((layer) => layer.setSpeed(0));
798
+ setObstacleSpeed(0);
799
+ dust.emitting = false;
800
+ sparks.x = player.x;
801
+ sparks.y = player.y;
802
+ sparks.emit(26);
803
+ gameView.shake({ strength: PLAYER * 0.12, duration: 450 });
804
+ }
805
+ ```
806
+
807
+ ## Rhythm game
808
+
809
+ 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.
810
+
811
+ ```javascript
812
+ const pads = LANES.map((x, lane) => {
813
+ const pad = Game.createSprite({ sheet: padSheet, x: x, y: PAD_Y, width: PAD, height: PAD, zIndex: 5 });
814
+ pad.addEventListener('press', () => hitLane(lane, pad));
815
+ gameView.add(pad);
816
+ return pad;
817
+ });
818
+
819
+ // gems must not swallow pad presses
820
+ const sprite = Game.createSprite({
821
+ sheet: noteSheet, width: NOTE, height: NOTE, zIndex: 10,
822
+ visible: false,
823
+ touchEnabled: false,
824
+ collidesWith: ['misszone']
825
+ });
826
+
827
+ function hitLane(lane, pad) {
828
+ pad.frame = 1;
829
+ setTimeout(() => {
830
+ pad.frame = 0;
831
+ }, 120);
832
+
833
+ let best = null;
834
+ let bestDistance = Infinity;
835
+ notes.forEach((note) => {
836
+ if (note.active && note.lane === lane) {
837
+ const distance = Math.abs(note.sprite.y - PAD_Y); // live native read
838
+ if (distance < bestDistance) {
839
+ bestDistance = distance;
840
+ best = note;
841
+ }
842
+ }
843
+ });
844
+
845
+ if (best !== null && bestDistance <= HIT_RANGE) {
846
+ recycle(best);
847
+ goodSound.play();
848
+ burst.x = LANES[lane];
849
+ burst.y = PAD_Y;
850
+ burst.tint = LANE_TINTS[lane];
851
+ burst.emit(18);
852
+ score += (bestDistance <= PERFECT) ? 3 : 1;
853
+ } else {
854
+ badSound.play();
855
+ }
856
+ }
857
+ ```
858
+
859
+ 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.
860
+
861
+ ## Ball sports / breakout physics
862
+
863
+ `restitution` on a circle-hitbox ball gives real reflection off walls and obstacles. Player contact is handled in JS so you control the feel.
864
+
865
+ ```javascript
866
+ const ball = Game.createSprite({
867
+ sheet: ballSheet,
868
+ x: W / 2, y: H * 0.3, width: BALL_SIZE, height: BALL_SIZE,
869
+ zIndex: 12,
870
+ hitboxScale: 0.9,
871
+ hitboxShape: 'circle', // bounces off the net's corner along the normal
872
+ restitution: 0.75,
873
+ solidWith: ['wall', 'net'], // blocked and bounced by these
874
+ collidesWith: ['player', 'floor'] // only reported for these
875
+ });
876
+
877
+ ball.addEventListener('collision', (e) => {
878
+ if (e.group === 'player') {
879
+ // reflect away from the blob's center, biased upward
880
+ const blob = e.other;
881
+ const dx = ball.x - blob.x;
882
+ const dy = ball.y - blob.y;
883
+ const len = Math.sqrt(dx * dx + dy * dy) || 1;
884
+ ball.velocityX = (dx / len) * HIT_SPEED;
885
+ ball.velocityY = Math.min((dy / len) * HIT_SPEED, -HIT_SPEED * 0.45);
886
+ } else if (e.group === 'floor') {
887
+ roundOver(ball.x > W / 2);
888
+ }
889
+ });
890
+ ```
891
+
892
+ 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.
893
+
894
+ A `restitution: 1` ball on an invisible floor bounces forever with no JS at all.
895
+
896
+ **Opponent AI** on an 80 ms timer, reading a handful of live properties per tick:
897
+
898
+ ```javascript
899
+ timer = setInterval(() => {
900
+ const onCpuSide = ball.x > W / 2;
901
+ const target = (running && onCpuSide) ? ball.x + PLAYER_SIZE * 0.2 : cpuHomeX;
902
+ const dx = target - cpu.x;
903
+ cpu.velocityX = (Math.abs(dx) > PLAYER_SIZE * 0.15) ? (dx > 0 ? RUN_SPEED : -RUN_SPEED) : 0;
904
+ if (running && onCpuSide && cpu.onGround
905
+ && Math.abs(ball.x - cpu.x) < PLAYER_SIZE * 1.2
906
+ && ball.y < cpu.y && ball.velocityY > 0) {
907
+ cpu.velocityY = -JUMP;
908
+ }
909
+ }, 80);
910
+ ```
911
+
912
+ ## Cards and board games
913
+
914
+ No physics at all — sprite taps, native tweens, glow and idle wobble.
915
+
916
+ **Dealing** staggers one tween per card with `delay`, and flips the art on arrival:
917
+
918
+ ```javascript
919
+ cards.forEach((card, index) => {
920
+ card.state = 'dealing';
921
+ card.sprite.idleAnimation = false; // still cards land exactly on target
922
+ card.sprite.frame = BACK_FRAME;
923
+ card.sprite.x = DECK_X;
924
+ card.sprite.y = DECK_Y;
925
+ card.sprite.zIndex = 30 + index; // above the deck while flying
926
+ card.sprite.animate({
927
+ x: card.home.x,
928
+ y: card.home.y,
929
+ rotation: card.home.rotation,
930
+ duration: 380,
931
+ delay: index * 140, // one card after another
932
+ easing: Game.EASE_IN_OUT
933
+ });
934
+ });
935
+
936
+ sprite.addEventListener('complete', () => {
937
+ if (card.state === 'dealing') {
938
+ card.state = 'hand';
939
+ sprite.frame = card.face; // flip face up on arrival
940
+ sprite.zIndex = card.index;
941
+ sprite.idleAnimation = true; // wobble only once it has settled
942
+ }
943
+ });
944
+ ```
945
+
946
+ **Selection** lifts the card and fades a glow in — `glowOpacity` is tweenable, so the halo appears with the movement instead of popping:
947
+
948
+ ```javascript
949
+ sprite.addEventListener('tap', () => {
950
+ if (card.selected) {
951
+ card.selected = false;
952
+ sprite.animate({ x: home.x, y: home.y, rotation: home.rotation, scale: 1, glowOpacity: 0, duration: 150, easing: Game.EASE_OUT });
953
+ } else if (selectedCards().length < MAX_SELECTED) {
954
+ card.selected = true;
955
+ sprite.glowColor = '#ffc94d';
956
+ sprite.glowBlur = CARD_W * 0.14;
957
+ sprite.glowOpacity = 0;
958
+ sprite.animate({ y: home.y - LIFT, scale: 1.12, glowOpacity: 1, duration: 150, easing: Game.EASE_OUT });
959
+ }
960
+ });
961
+ ```
962
+
963
+ **Drag & drop with snapping** (puzzle pieces, board tiles). The drag itself is native; you only decide where it lands:
964
+
965
+ ```javascript
966
+ const piece = Game.createSprite({ sheet: sheet, frame: index, x: homeX, y: homeY, width: PIECE, height: PIECE, draggable: true, zIndex: 10 });
967
+
968
+ piece.addEventListener('press', () => {
969
+ piece.zIndex = 100; // draw above everything while held
970
+ piece.animate({ scale: 1.15, duration: 120, easing: Game.EASE_OUT });
971
+ });
972
+
973
+ piece.addEventListener('release', () => {
974
+ piece.animate({ scale: 1, duration: 120, easing: Game.EASE_OUT });
975
+ });
976
+
977
+ piece.addEventListener('dragend', (e) => {
978
+ let best = null;
979
+ let bestDistance = SNAP_DISTANCE;
980
+ cells.forEach((cell) => {
981
+ if (cell.piece) {
982
+ return;
983
+ }
984
+ const d = Math.sqrt(Math.pow(e.x - cell.x, 2) + Math.pow(e.y - cell.y, 2));
985
+ if (d < bestDistance) {
986
+ bestDistance = d;
987
+ best = cell;
988
+ }
989
+ });
990
+ piece.zIndex = 10;
991
+ if (best) {
992
+ best.piece = piece;
993
+ piece.animate({ x: best.x, y: best.y, duration: 150, easing: Game.EASE_OUT });
994
+ } else {
995
+ piece.animate({ x: homeX, y: homeY, duration: 400, easing: Game.EASE_IN_OUT });
996
+ }
997
+ });
998
+ ```
999
+
1000
+ Because every handler is per sprite, this is multi-touch for free: each finger grabs its own piece.
1001
+
1002
+ ## Point & click adventure
1003
+
1004
+ Tap-to-walk with a distance-sized tween gives constant walking speed regardless of distance:
1005
+
1006
+ ```javascript
1007
+ function walkTo(x, y) {
1008
+ const targetX = Math.min(Math.max(x, W * 0.06), W * 0.94);
1009
+ const targetY = Math.min(Math.max(y, WALK_TOP), H * 0.95) - PLAYER_H / 2;
1010
+ const distance = Math.sqrt(Math.pow(targetX - player.x, 2) + Math.pow(targetY - player.y, 2));
1011
+ if (distance < 4) {
1012
+ return;
1013
+ }
1014
+ player.scaleX = targetX < player.x ? -1 : 1;
1015
+ player.clearTweens(); // cancel a walk in progress
1016
+ player.play('walk');
1017
+ player.animate({
1018
+ x: targetX,
1019
+ y: targetY,
1020
+ duration: distance / WALK_SPEED * 1000, // constant px/s
1021
+ easing: Game.EASE_LINEAR // no ease on a walk
1022
+ });
1023
+ }
1024
+
1025
+ player.addEventListener('complete', () => player.play('idle'));
1026
+ ```
1027
+
1028
+ The walkable floor is a clamp (`WALK_TOP`), not geometry — no collision needed for a classic adventure floor.
1029
+
1030
+ **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:
1031
+
1032
+ ```javascript
1033
+ function over(sprite, x, y) {
1034
+ return sprite.visible !== false
1035
+ && Math.abs(x - sprite.x) <= sprite.width / 2 + PAD
1036
+ && Math.abs(y - sprite.y) <= sprite.height / 2 + PAD;
1037
+ }
1038
+
1039
+ gameView.addEventListener('tap', (e) => {
1040
+ if (over(bird, e.x, e.y) || over(handIcon, e.x, e.y) || over(talkIcon, e.x, e.y)) {
1041
+ return;
1042
+ }
1043
+ hideIcons();
1044
+ walkTo(e.x, e.y);
1045
+ });
1046
+ ```
1047
+
1048
+ A verb coin is two icon sprites with `visible` toggled and `idleAnimation: true` for a bit of life while open.
1049
+
1050
+ ## Particles
1051
+
1052
+ Three modes, all native. Tint white art at runtime so one 16×16 texture covers every effect in the game.
1053
+
1054
+ **Continuous fountain**:
1055
+
1056
+ ```javascript
1057
+ const fountain = Game.createEmitter({
1058
+ sheet: sparkSheet, frame: 1,
1059
+ x: W / 2, y: H - UNIT * 0.05,
1060
+ rate: 90,
1061
+ lifetime: 1600,
1062
+ speed: H * 0.75, // launch up...
1063
+ angle: 0, // 0 = up, clockwise degrees
1064
+ spread: 25,
1065
+ gravity: H * 0.45, // ...and fall back
1066
+ size: UNIT * 0.03,
1067
+ startScale: 1, endScale: 0.4,
1068
+ startOpacity: 1, endOpacity: 0,
1069
+ tint: '#ffcc44',
1070
+ maxParticles: 400
1071
+ });
1072
+ gameView.add(fountain);
1073
+ ```
1074
+
1075
+ **Burst on demand** — `rate: 0`, position it and call `emit(n)`:
1076
+
1077
+ ```javascript
1078
+ const firework = Game.createEmitter({
1079
+ sheet: sparkSheet, frame: 1,
1080
+ rate: 0,
1081
+ lifetime: 900,
1082
+ speed: UNIT * 0.6,
1083
+ spread: 360,
1084
+ gravity: H * 0.25,
1085
+ startScale: 1, endScale: 0.3,
1086
+ maxParticles: 500
1087
+ });
1088
+ gameView.add(firework);
1089
+
1090
+ gameView.addEventListener('tap', (e) => {
1091
+ firework.x = e.x;
1092
+ firework.y = e.y;
1093
+ firework.tint = COLORS[colorIndex++ % COLORS.length];
1094
+ firework.emit(45);
1095
+ });
1096
+ ```
1097
+
1098
+ **Trail following a sprite** — `target` keeps up even mid-drag, with no bridge traffic:
1099
+
1100
+ ```javascript
1101
+ const dust = Game.createEmitter({
1102
+ sheet: sparkSheet, frame: 0,
1103
+ target: player,
1104
+ offsetX: -PLAYER * 0.32, // behind the rear wheels
1105
+ offsetY: PLAYER * 0.42,
1106
+ rate: 22,
1107
+ lifetime: 450,
1108
+ speed: W * 0.08,
1109
+ angle: -35, // up and back
1110
+ spread: 50,
1111
+ startOpacity: 0.45, endOpacity: 0,
1112
+ tint: '#8a8580',
1113
+ zIndex: 9 // behind the player
1114
+ });
1115
+ gameView.add(dust);
1116
+
1117
+ dust.emitting = false; // the one property JS toggles at runtime
1118
+ ```
1119
+
1120
+ Add `blend: 'add'` for fire, magic and sparks — overlaps bloom instead of covering.
1121
+
1122
+ ## Ropes and chains
1123
+
1124
+ ```javascript
1125
+ // hangs from a draggable ball
1126
+ const ball = Game.createSprite({ sheet: ballSheet, x: W / 2, y: H * 0.22, width: BALL, height: BALL, zIndex: 10, draggable: true, hitboxShape: 'circle' });
1127
+ gameView.add(ball);
1128
+
1129
+ gameView.add(Game.createRope({
1130
+ sheet: ropeSheet,
1131
+ segments: 14,
1132
+ segmentLength: H * 0.04,
1133
+ thickness: W * 0.03,
1134
+ gravity: H * 1.6,
1135
+ damping: 0.985,
1136
+ iterations: 3,
1137
+ head: ball, // pinned to the sprite — drag it and the rope follows
1138
+ zIndex: 5
1139
+ }));
1140
+
1141
+ // fixed anchor + a weight on a tether: drag it too far and it is pulled back
1142
+ gameView.add(Game.createRope({
1143
+ sheet: ropeSheet,
1144
+ segments: 10,
1145
+ segmentLength: SEG_LEN,
1146
+ gravity: H * 1.6,
1147
+ x: W * 0.15, y: H * 0.1, // fixed head anchor
1148
+ tail: weight,
1149
+ maxLength: 10 * SEG_LEN, // wrecking balls, leashes, yo-yos
1150
+ zIndex: 5
1151
+ }));
1152
+ ```
1153
+
1154
+ 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`.
1155
+
1156
+ ## Camera work
1157
+
1158
+ ```javascript
1159
+ gameView.follow(player, {
1160
+ leftMargin: 0.4, rightMargin: 0.6, // horizontal follow is off without these
1161
+ topMargin: 0.4, bottomMargin: 0.6,
1162
+ smoothing: 0.12, // 0 snaps; higher eases
1163
+ maxY: WORLD_H // default 0 clamps to the top of the world
1164
+ });
1165
+ gameView.cameraBounds = { minX: 0, minY: 0, maxX: WORLD_W, maxY: WORLD_H };
1166
+ ```
1167
+
1168
+ 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.
1169
+
1170
+ ```javascript
1171
+ gameView.cameraScale = Math.min(2.5, Math.max(0.5, gameView.cameraScale * 1.25)); // zoom
1172
+ gameView.shake({ strength: W * 0.02, duration: 500 }); // impact
1173
+ gameView.cameraEffect = 'tint'; // night vision
1174
+ gameView.cameraTint = '#4f8';
1175
+ gameView.cameraEffectIntensity = 0.7;
1176
+ gameView.cameraEffect = 'glitch'; // broken signal
1177
+ gameView.cameraEffect = 'none'; // skips the pass entirely
1178
+ ```
1179
+
1180
+ 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.
1181
+
1182
+ ## Visual effects
1183
+
1184
+ **`blend: 'add'`** — identical sprites, different blend: normal overlaps cover each other, additive overlaps sum and bloom toward white. Use it for glows, fire, lasers and light shafts, and group additive sprites on their own `zIndex` band since each blend change costs a batch flush.
1185
+
1186
+ **`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.
1187
+
1188
+ **`flipX` / `flipY` from movement** — mirror the drawn frame without touching physics:
1189
+
1190
+ ```javascript
1191
+ // tween patrol: flip on each turn-around
1192
+ function patrol() {
1193
+ const goingRight = bird.x < W / 2;
1194
+ bird.flipX = !goingRight;
1195
+ bird.animate({ x: goingRight ? W - MARGIN : MARGIN, duration: 3000, easing: Game.EASE_IN_OUT });
1196
+ }
1197
+ bird.addEventListener('complete', patrol);
1198
+
1199
+ // velocity runner: a slow watchdog turns it around, never moves it
1200
+ timer = setInterval(() => {
1201
+ [dog, player].forEach((runner) => {
1202
+ if (runner.velocityX > 0 && runner.x > W - MARGIN) {
1203
+ runner.velocityX = -runner.velocityX;
1204
+ } else if (runner.velocityX < 0 && runner.x < MARGIN) {
1205
+ runner.velocityX = -runner.velocityX;
1206
+ }
1207
+ runner.flipX = runner.velocityX < 0;
1208
+ });
1209
+ }, 150);
1210
+
1211
+ // VVVVVV-style gravity inversion
1212
+ gameView.addEventListener('tap', () => {
1213
+ player.gravity = -player.gravity;
1214
+ player.flipY = player.gravity < 0;
1215
+ });
1216
+ ```
1217
+
1218
+ **`timeScale`** — one property slows or freezes physics, sheet animations, tweens, particles and the camera 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.
1219
+
1220
+ **`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.