littlejsengine 1.18.29 → 1.20.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.
Files changed (51) hide show
  1. package/FAQ.md +841 -815
  2. package/README.md +211 -199
  3. package/dist/littlejs.d.ts +4383 -812
  4. package/dist/littlejs.esm.js +31848 -16680
  5. package/dist/littlejs.esm.min.js +14 -1
  6. package/dist/littlejs.js +31230 -16166
  7. package/dist/littlejs.min.js +13 -1
  8. package/dist/littlejs.release.js +27419 -15457
  9. package/package.json +10 -5
  10. package/plugins/audioEffects.js +375 -0
  11. package/plugins/box2d.js +2516 -2073
  12. package/plugins/drawUtilities.js +206 -31
  13. package/plugins/gltf.js +740 -0
  14. package/plugins/jsconfig.json +19 -0
  15. package/plugins/lightSystem.js +719 -330
  16. package/plugins/math3d.js +911 -0
  17. package/plugins/medalSystem.js +118 -72
  18. package/plugins/newgrounds.js +400 -199
  19. package/plugins/pathFinder.js +208 -175
  20. package/plugins/pluginExport.js +196 -115
  21. package/plugins/postProcess.js +284 -166
  22. package/plugins/render3d.js +4072 -0
  23. package/plugins/render3dDebug.js +109 -0
  24. package/plugins/render3dExtras.js +1754 -0
  25. package/plugins/render3dVoxels.js +502 -0
  26. package/plugins/textureSheet.js +86 -48
  27. package/plugins/threejs.js +183 -158
  28. package/plugins/tweakables.js +411 -0
  29. package/plugins/tweenSystem.js +646 -526
  30. package/plugins/uiSystem.js +2024 -1687
  31. package/plugins/zzfxm.js +8 -15
  32. package/src/engine.js +345 -194
  33. package/src/engineAudio.js +1022 -777
  34. package/src/engineBuild.mjs +289 -253
  35. package/src/engineDebug.js +912 -735
  36. package/src/engineDraw.js +1774 -1510
  37. package/src/engineEditor.js +2431 -0
  38. package/src/engineExport.js +419 -396
  39. package/src/engineInput.js +1462 -1293
  40. package/src/engineLogo.js +4 -3
  41. package/src/engineMath.js +1274 -1183
  42. package/src/engineObject.js +674 -551
  43. package/src/engineParticles.js +583 -532
  44. package/src/engineRelease.js +67 -45
  45. package/src/engineSettings.js +808 -726
  46. package/src/engineTileLayer.js +995 -741
  47. package/src/engineUtilities.js +32 -13
  48. package/src/engineWebGL.js +1162 -941
  49. package/src/jsconfig.json +17 -13
  50. package/plugins/box2d.wasm.js +0 -630
  51. package/plugins/box2d.wasm.wasm +0 -0
@@ -1,552 +1,675 @@
1
- /**
2
- * LittleJS Object System
3
- * - EngineObject is the base class for all game objects
4
- * - Handles automatic updating, rendering, physics, and collision
5
- * - Supports parent-child hierarchies with transform inheritance
6
- * - 2D physics with velocity, acceleration, damping, and gravity
7
- * - Collision system with tiles and other objects
8
- * - Renders sprites from tile sheets with color and rotation
9
- * - Objects sorted by renderOrder for layered rendering
10
- */
11
-
12
- 'use strict';
13
-
14
- /**
15
- * LittleJS Object Base Object Class
16
- * - Top level object class used by the engine
17
- * - Automatically adds self to object list
18
- * - Will be updated and rendered each frame
19
- * - Renders as a sprite from a tilesheet by default
20
- * - Can have color and additive color applied
21
- * - 2D Physics and collision system
22
- * - Sorted by renderOrder
23
- * - Objects can have children attached
24
- * - Parents are updated before children, and set child transform
25
- * - Call destroy() to get rid of objects
26
- *
27
- * The physics system used by objects is simple and fast with some caveats...
28
- * - Collision uses the axis aligned size, the object's rotation angle is only for rendering
29
- * - Objects are guaranteed to not intersect tile collision from physics
30
- * - If an object starts or is moved inside tile collision, it will not collide with that tile
31
- * - Collision for objects can be set to be solid to block other objects
32
- * - Objects may get pushed into overlapping other solid objects, if so they will push away
33
- * - Solid objects are more performance intensive and should be used sparingly
34
- * @memberof Engine
35
- * @example
36
- * // create an engine object, normally you would first extend the class with your own
37
- * const pos = vec2(2,3);
38
- * const object = new EngineObject(pos);
39
- */
40
- class EngineObject
41
- {
42
- /** Create an engine object and adds it to the list of objects
43
- * @param {Vector2} [pos=vec2()] - World space position of the object
44
- * @param {Vector2} [size=vec2(1)] - World space size of the object
45
- * @param {TileInfo} [tileInfo] - Tile info to render object (undefined is untextured)
46
- * @param {number} [angle] - Angle the object is rotated by
47
- * @param {Color} [color=WHITE] - Color to apply to tile when rendered
48
- * @param {number} [renderOrder] - Objects sorted by renderOrder before being rendered
49
- */
50
- constructor(pos=vec2(), size=vec2(1), tileInfo, angle=0, color=WHITE, renderOrder=0)
51
- {
52
- // check passed in params
53
- ASSERT(isVector2(pos), 'object pos must be a vec2');
54
- ASSERT(isVector2(size), 'object size must be a vec2');
55
- ASSERT(!tileInfo || tileInfo instanceof TileInfo, 'object tileInfo should be a TileInfo or undefined');
56
- ASSERT(typeof angle === 'number' && isFinite(angle), 'object angle should be a number');
57
- ASSERT(isColor(color), 'object color should be a valid rgba color');
58
- ASSERT(typeof renderOrder === 'number', 'object renderOrder should be a number');
59
-
60
- /** @property {Vector2} - World space position of the object */
61
- this.pos = pos.copy();
62
- /** @property {Vector2} - World space width and height of the object */
63
- this.size = size.copy();
64
- /** @property {Vector2} - Size of object used for drawing, uses size if not set */
65
- this.drawSize = undefined;
66
- /** @property {TileInfo} - Tile info to render object (undefined is untextured) */
67
- this.tileInfo = tileInfo;
68
- /** @property {number} - Angle to rotate the object */
69
- this.angle = angle;
70
- /** @property {Color} - Color to apply when rendered */
71
- this.color = color.copy();
72
- /** @property {Color} - Additive color to apply when rendered */
73
- this.additiveColor = undefined;
74
- /** @property {boolean} - Should the rendered tile flip along the y axis. Affects rendering and the local→world transform of attached children (a mirrored parent flips its children's localPos.x and localAngle). Does not affect this object's own physics, collision, or localToWorld/worldToLocal. */
75
- this.mirror = false;
76
- /** @property {boolean} - Has object been destroyed? */
77
- this.destroyed = false;
78
-
79
- // physical properties
80
- /** @property {number} - How heavy the object is, static if 0 */
81
- this.mass = objectDefaultMass;
82
- /** @property {number} - How much to slow down velocity each frame (0-1) */
83
- this.damping = objectDefaultDamping;
84
- /** @property {number} - How much to slow down rotation each frame (0-1) */
85
- this.angleDamping = objectDefaultAngleDamping;
86
- /** @property {number} - How bouncy the object is when colliding (0-1) */
87
- this.restitution = objectDefaultRestitution;
88
- /** @property {number} - How much friction to apply when sliding (0-1) */
89
- this.friction = objectDefaultFriction;
90
- /** @property {number} - How much to scale gravity by for this object */
91
- this.gravityScale = 1;
92
- /** @property {number} - Objects are sorted by render order */
93
- this.renderOrder = renderOrder;
94
- /** @property {Vector2} - Velocity of the object */
95
- this.velocity = vec2();
96
- /** @property {number} - Angular velocity of the object */
97
- this.angleVelocity = 0;
98
- /** @property {number} - Track when object was created */
99
- this.spawnTime = time;
100
- /** @property {Array<EngineObject>} - List of children of this object */
101
- this.children = [];
102
- /** @property {boolean} - Limit object speed along x and y axis */
103
- this.clampSpeed = true;
104
- /** @property {EngineObject} - Object we are standing on, if any */
105
- this.groundObject = undefined;
106
-
107
- // parent child system
108
- /** @property {EngineObject} - Parent of object if in local space */
109
- this.parent = undefined;
110
- /** @property {Vector2} - Local position if child */
111
- this.localPos = vec2();
112
- /** @property {number} - Local angle if child */
113
- this.localAngle = 0;
114
-
115
- // collision flags
116
- /** @property {boolean} - Object collides with the tile collision */
117
- this.collideTiles = false;
118
- /** @property {boolean} - Object collides with solid objects */
119
- this.collideSolidObjects = false;
120
- /** @property {boolean} - Object collides with and blocks other objects */
121
- this.isSolid = false;
122
- /** @property {boolean} - Object collides with raycasts */
123
- this.collideRaycast = false;
124
-
125
- // add to list of objects
126
- engineObjects.push(this);
127
- }
128
-
129
- /** Update the object transform, called automatically by engine even when paused */
130
- updateTransforms()
131
- {
132
- const parent = this.parent;
133
- if (parent)
134
- {
135
- // compose with parent transform inline to avoid intermediate vector allocs
136
- const mirror = parent.getMirrorSign();
137
- const lp = this.localPos, pp = parent.pos;
138
- const lx = lp.x*mirror, ly = lp.y, pa = parent.angle;
139
- if (pa)
140
- {
141
- const c = cos(-pa), s = sin(-pa);
142
- this.pos.set(lx*c - ly*s + pp.x, lx*s + ly*c + pp.y);
143
- }
144
- else
145
- this.pos.set(lx + pp.x, ly + pp.y);
146
- this.angle = mirror*this.localAngle + pa;
147
- }
148
-
149
- // update children
150
- for (const child of this.children)
151
- child.updateTransforms();
152
- }
153
-
154
- /** Update the object physics, called automatically by engine once each frame. Can be overridden to stop or change how physics works for an object. */
155
- updatePhysics()
156
- {
157
- // child objects do not have physics
158
- ASSERT(!this.parent);
159
-
160
- // bail if a collision callback destroyed us mid-frame
161
- if (this.destroyed) return;
162
-
163
- if (this.clampSpeed)
164
- {
165
- // limit max speed to prevent missing collisions
166
- this.velocity.x = clamp(this.velocity.x, -objectMaxSpeed, objectMaxSpeed);
167
- this.velocity.y = clamp(this.velocity.y, -objectMaxSpeed, objectMaxSpeed);
168
- }
169
-
170
- // apply physics
171
- const oldPos = this.pos.copy();
172
- this.velocity.x *= this.damping;
173
- this.velocity.y *= this.damping;
174
- if (this.mass)
175
- {
176
- // apply gravity only if it has mass
177
- this.velocity.x += gravity.x * this.gravityScale;
178
- this.velocity.y += gravity.y * this.gravityScale;
179
- }
180
- this.pos.x += this.velocity.x;
181
- this.pos.y += this.velocity.y;
182
- this.angle += this.angleVelocity *= this.angleDamping;
183
-
184
- // physics sanity checks
185
- ASSERT(this.angleDamping >= 0 && this.angleDamping <= 1);
186
- ASSERT(this.damping >= 0 && this.damping <= 1);
187
-
188
- // don't do collision for static objects or if solver disabled
189
- if (!enablePhysicsSolver || !this.mass) return;
190
-
191
- const wasFalling = this.velocity.y < 0 && gravity.y < 0 || this.velocity.y > 0 && gravity.y > 0;
192
- if (this.groundObject)
193
- {
194
- // apply friction in local space of ground object
195
- const friction = max(this.friction, this.groundObject.friction);
196
- const groundSpeed = this.groundObject.velocity.x;
197
- this.velocity.x = groundSpeed + (this.velocity.x - groundSpeed) * friction;
198
- this.groundObject = undefined;
199
- }
200
-
201
- if (this.collideSolidObjects)
202
- {
203
- // check collisions against solid objects
204
- const epsilon = .001; // necessary to push slightly outside of the collision
205
- for (const o of engineObjectsCollide)
206
- {
207
- // skip destroyed, child objects, or self collision
208
- if (o.destroyed || o.parent || o === this) continue;
209
-
210
- // non solid objects don't collide with each other
211
- if (!this.isSolid && !o.isSolid) continue;
212
-
213
- // check collision
214
- if (!this.isOverlappingObject(o)) continue;
215
-
216
- // notify objects of collision and check if should be resolved
217
- const collide1 = this.collideWithObject(o);
218
- const collide2 = o.collideWithObject(this);
219
- if (!collide1 || !collide2) continue;
220
-
221
- if (isOverlapping(oldPos, this.size, o.pos, o.size))
222
- {
223
- // if already was touching, try to push away
224
- const deltaPos = oldPos.subtract(o.pos);
225
- const length = deltaPos.length();
226
- const pushAwayAccel = .001;
227
- const velocity = length < .001 ? vec2(0,1) : deltaPos.scale(pushAwayAccel/length);
228
- this.velocity = this.velocity.add(velocity);
229
- if (o.mass) // push away other object if not fixed
230
- o.velocity = o.velocity.subtract(velocity);
231
-
232
- debugPhysics && debugOverlap(this.pos, this.size, o.pos, o.size, '#f00');
233
- continue;
234
- }
235
-
236
- // check for collision
237
- const sizeBoth = this.size.add(o.size);
238
- const smallStepUp = (oldPos.y - o.pos.y)*2 > sizeBoth.y + gravity.y; // prefer to push up if small delta
239
- const isBlockedX = abs(oldPos.y - o.pos.y)*2 < sizeBoth.y;
240
- const isBlockedY = abs(oldPos.x - o.pos.x)*2 < sizeBoth.x;
241
- const restitution = max(this.restitution, o.restitution);
242
-
243
- if (smallStepUp || isBlockedY || !isBlockedX) // resolve y collision
244
- {
245
- // push outside object collision
246
- this.pos.y = o.pos.y + (sizeBoth.y/2 + epsilon) * sign(oldPos.y - o.pos.y);
247
- if ((o.groundObject && wasFalling) || !o.mass)
248
- {
249
- // set ground object if landed on something
250
- if (wasFalling)
251
- this.groundObject = o;
252
-
253
- // bounce if other object is fixed or grounded
254
- this.velocity.y *= -restitution;
255
- }
256
- else if (o.mass)
257
- {
258
- // inelastic collision
259
- const inelastic = (this.mass * this.velocity.y + o.mass * o.velocity.y) / (this.mass + o.mass);
260
-
261
- // elastic collision
262
- const elastic0 = this.velocity.y * (this.mass - o.mass) / (this.mass + o.mass)
263
- + o.velocity.y * 2 * o.mass / (this.mass + o.mass);
264
- const elastic1 = o.velocity.y * (o.mass - this.mass) / (this.mass + o.mass)
265
- + this.velocity.y * 2 * this.mass / (this.mass + o.mass);
266
-
267
- // lerp between elastic or inelastic based on restitution
268
- this.velocity.y = lerp(inelastic, elastic0, restitution);
269
- o.velocity.y = lerp(inelastic, elastic1, restitution);
270
- }
271
- }
272
- if (!smallStepUp && isBlockedX) // resolve x collision
273
- {
274
- // push outside collision
275
- this.pos.x = o.pos.x + (sizeBoth.x/2 + epsilon) * sign(oldPos.x - o.pos.x);
276
- if (o.mass)
277
- {
278
- // inelastic collision
279
- const inelastic = (this.mass * this.velocity.x + o.mass * o.velocity.x) / (this.mass + o.mass);
280
-
281
- // elastic collision
282
- const elastic0 = this.velocity.x * (this.mass - o.mass) / (this.mass + o.mass)
283
- + o.velocity.x * 2 * o.mass / (this.mass + o.mass);
284
- const elastic1 = o.velocity.x * (o.mass - this.mass) / (this.mass + o.mass)
285
- + this.velocity.x * 2 * this.mass / (this.mass + o.mass);
286
-
287
- // lerp between elastic or inelastic based on restitution
288
- this.velocity.x = lerp(inelastic, elastic0, restitution);
289
- o.velocity.x = lerp(inelastic, elastic1, restitution);
290
- }
291
- else // bounce if other object is fixed
292
- this.velocity.x *= -restitution;
293
- }
294
- debugPhysics && debugOverlap(this.pos, this.size, o.pos, o.size, '#f0f');
295
- }
296
- }
297
- if (this.collideTiles)
298
- {
299
- // check collision against tiles
300
- const hitLayer = tileCollisionTest(this.pos, this.size, this);
301
- if (hitLayer)
302
- {
303
- // if already was stuck in collision, don't do anything
304
- // this should not happen unless something starts in collision
305
- if (!tileCollisionTest(oldPos, this.size, this))
306
- {
307
- // test which side we bounced off (or both if a corner)
308
- const isBlockedX = tileCollisionTest(vec2(this.pos.x, oldPos.y), this.size, this);
309
- const isBlockedY = tileCollisionTest(vec2(oldPos.x, this.pos.y), this.size, this);
310
- const restitution = max(this.restitution, hitLayer.restitution);
311
- if (isBlockedX)
312
- {
313
- // try to step over a 1-tile bump (direction follows gravity sign
314
- // so inverted gravity steps down off a ceiling bump instead of up;
315
- // zero gravity defaults to the normal-gravity step-up direction)
316
- const epsilon = 1e-3;
317
- const maxMove = .1;
318
- const gravitySign = gravity.y > 0 ? -1 : 1;
319
- const y = gravitySign > 0 ?
320
- floor(oldPos.y-this.size.y/2+1) + this.size.y/2 + epsilon :
321
- ceil( oldPos.y+this.size.y/2-1) - this.size.y/2 - epsilon;
322
- const delta = abs(y - this.pos.y);
323
- if (delta < maxMove)
324
- if (!tileCollisionTest(vec2(this.pos.x, y), this.size, this))
325
- {
326
- this.pos.y = y;
327
- debugPhysics && debugRect(this.pos, this.size, '#ff0');
328
- return;
329
- }
330
-
331
- // move to previous X position and bounce
332
- this.pos.x = oldPos.x;
333
- this.velocity.x *= -restitution;
334
- }
335
- if (isBlockedY || !isBlockedX)
336
- {
337
- if (wasFalling)
338
- {
339
- // adjust position to slightly away from nearest tile
340
- // this prevents gap between object and ground
341
- const epsilon = .0001;
342
- const offset = this.size.y/2 + epsilon;
343
- this.pos.y = gravity.y < 0 ?
344
- floor(oldPos.y-this.size.y/2) + offset :
345
- ceil( oldPos.y+this.size.y/2) - offset;
346
-
347
- // set ground object for tile collision
348
- this.groundObject = hitLayer;
349
- }
350
- else
351
- {
352
- // move to previous Y position
353
- this.pos.y = oldPos.y;
354
- this.groundObject = undefined;
355
- }
356
- // bounce velocity
357
- this.velocity.y *= -restitution;
358
- }
359
- debugPhysics && debugRect(this.pos, this.size, '#f00');
360
- }
361
- }
362
- }
363
- }
364
-
365
- /** Update the object, called automatically by engine once each frame. Does nothing by default. */
366
- update() {}
367
-
368
- /** Render the object, draws a tile by default, automatically called each frame, sorted by renderOrder */
369
- render()
370
- {
371
- // default object render
372
- drawTile(this.pos, this.drawSize || this.size, this.tileInfo, this.color, this.angle, this.mirror, this.additiveColor);
373
- }
374
-
375
- /** Optional hook called during the light system plugin's lightmap pass to draw this object's lightmap contribution. Does nothing by default. */
376
- renderLight() {}
377
-
378
- /** Destroy this object, destroy its children, detach its parent, and mark it for removal
379
- * @param {boolean} [immediate] - should attached effects be allowed to die off? */
380
- destroy(immediate=false)
381
- {
382
- if (this.destroyed) return;
383
-
384
- // disconnect from parent and destroy children
385
- this.destroyed = true;
386
- this.parent?.removeChild(this);
387
- for (const child of this.children)
388
- {
389
- child.parent = undefined;
390
- child.destroy(immediate);
391
- }
392
- }
393
-
394
- /** Convert from local space to world space
395
- * @param {Vector2} pos - local space point */
396
- localToWorld(pos) { return this.pos.add(pos.rotate(this.angle)); }
397
-
398
- /** Convert from world space to local space
399
- * @param {Vector2} pos - world space point */
400
- worldToLocal(pos) { return pos.subtract(this.pos).rotate(-this.angle); }
401
-
402
- /** Convert from local space to world space for a vector (rotation only)
403
- * @param {Vector2} vec - local space vector */
404
- localToWorldVector(vec) { return vec.rotate(this.angle); }
405
-
406
- /** Convert from world space to local space for a vector (rotation only)
407
- * @param {Vector2} vec - world space vector */
408
- worldToLocalVector(vec) { return vec.rotate(-this.angle); }
409
-
410
- /** Called to check if a tile collision should be resolved. Return true for physics to resolve the collision or false to ignore and resolve it manually.
411
- * @param {number} tileData - the value of the tile at the position
412
- * @param {Vector2} pos - tile where the collision occurred
413
- * @return {boolean} - true if the collision should be resolved by modifying it's position and velocity */
414
- collideWithTile(tileData, pos) { return tileData > 0; }
415
-
416
- /** Called by the engine to check if an object collision should be resolved. Return true for physics to resolve the collision or false to ignore and resolve it manually.
417
- * @param {EngineObject} object - the object to test against
418
- * @return {boolean} - true if the collision should be resolved by modifying it's position and velocity
419
- */
420
- collideWithObject(object) { return true; }
421
-
422
- /** Get this object's up vector
423
- * @param {number} [scale] - length of the vector
424
- * @return {Vector2} */
425
- getUp(scale=1) { return vec2().setAngle(this.angle, scale); }
426
-
427
- /** Get this object's right vector
428
- * @param {number} [scale] - length of the vector
429
- * @return {Vector2} */
430
- getRight(scale=1) { return vec2().setAngle(this.angle+PI/2, scale); }
431
-
432
- /** How long since the object was created
433
- * @return {number} */
434
- getAliveTime() { return time - this.spawnTime; }
435
-
436
- /** Get the speed of this object
437
- * @return {number} */
438
- getSpeed() { return this.velocity.length(); }
439
-
440
- /** Apply acceleration to this object (adjust velocity, not affected by mass)
441
- * @param {Vector2} acceleration */
442
- applyAcceleration(acceleration)
443
- { if (this.mass) this.velocity = this.velocity.add(acceleration); }
444
-
445
- /** Apply angular acceleration to this object
446
- * @param {number} acceleration */
447
- applyAngularAcceleration(acceleration)
448
- { if (this.mass) this.angleVelocity += acceleration; }
449
-
450
- /** Apply force to this object (adjust velocity, affected by mass)
451
- * @param {Vector2} force */
452
- applyForce(force)
453
- { if (this.mass) this.applyAcceleration(force.scale(1/this.mass)); }
454
-
455
- /** Get the direction of the mirror
456
- * @return {number} -1 if this.mirror is true, or 1 if not mirrored */
457
- getMirrorSign() { return this.mirror ? -1 : 1; }
458
-
459
- /** Attaches a child to this with a local transform, returns child for chaining
460
- * @param {EngineObject} child
461
- * @param {Vector2} [localPos=vec2()]
462
- * @param {number} [localAngle]
463
- * @return {EngineObject} The child object added */
464
- addChild(child, localPos=vec2(), localAngle=0)
465
- {
466
- ASSERT(!this.destroyed, 'cannot add child to destroyed object');
467
- if (this.destroyed) return child;
468
- ASSERT(!child.parent && !this.children.includes(child));
469
- ASSERT(child instanceof EngineObject, 'child must be an EngineObject');
470
- ASSERT(child !== this, 'cannot add self as child');
471
- this.children.push(child);
472
- child.parent = this;
473
- child.localPos = localPos.copy();
474
- child.localAngle = localAngle;
475
- child.updateTransforms();
476
- return child;
477
- }
478
-
479
- /** Removes a child from this one
480
- * @param {EngineObject} child */
481
- removeChild(child)
482
- {
483
- ASSERT(child.parent === this && this.children.includes(child));
484
- this.children.splice(this.children.indexOf(child), 1);
485
- child.parent = undefined;
486
- }
487
-
488
- /** Check if overlapping another engine object
489
- * Collisions are resolved to prevent overlaps
490
- * @param {EngineObject} object
491
- * @return {boolean} */
492
- isOverlappingObject(object)
493
- { return this.isOverlapping(object.pos, object.size); }
494
-
495
- /** Check if overlapping a point or aligned bounding box
496
- * @param {Vector2} pos - Center of box
497
- * @param {Vector2} [size=vec2()] - Size of box, uses a point if undefined
498
- * @return {boolean} */
499
- isOverlapping(pos, size=vec2())
500
- { return isOverlapping(this.pos, this.size, pos, size); }
501
-
502
- /** Set how this object collides
503
- * @param {boolean} [collideSolidObjects] - Does it collide with solid objects?
504
- * @param {boolean} [isSolid] - Does it collide with and block other objects? (expensive in large numbers)
505
- * @param {boolean} [collideTiles] - Does it collide with the tile collision?
506
- * @param {boolean} [collideRaycast] - Does it collide with raycasts? */
507
- setCollision(collideSolidObjects=true, isSolid=true, collideTiles=true, collideRaycast=true)
508
- {
509
- ASSERT(collideSolidObjects || !isSolid, 'solid objects must be set to collide');
510
-
511
- this.collideSolidObjects = collideSolidObjects;
512
- this.isSolid = isSolid;
513
- this.collideTiles = collideTiles;
514
- this.collideRaycast = collideRaycast;
515
- }
516
-
517
- /** Returns string containing info about this object for debugging
518
- * @return {string} */
519
- toString()
520
- {
521
- let text = 'type = ' + this.constructor.name;
522
- if (this.pos.x || this.pos.y)
523
- text += '\npos = ' + this.pos;
524
- if (this.velocity.x || this.velocity.y)
525
- text += '\nvelocity = ' + this.velocity;
526
- if (this.size.x || this.size.y)
527
- text += '\nsize = ' + this.size;
528
- if (this.angle)
529
- text += '\nangle = ' + this.angle.toFixed(3);
530
- if (this.color)
531
- text += '\ncolor = ' + this.color;
532
- return text;
533
- }
534
-
535
- /** Render debug info for this object */
536
- renderDebugInfo()
537
- {
538
- if (!debug) return;
539
-
540
- // check if there is anything to show
541
- const hasPhysics = this.collideTiles || this.collideSolidObjects || this.isSolid;
542
- if (!hasPhysics && !this.parent) return;
543
-
544
- // show object info for debugging
545
- const size = vec2(max(this.size.x, .2), max(this.size.y, .2));
546
- const color = rgb(this.collideTiles?1:0, this.collideSolidObjects?1:0, this.isSolid?1:0, .5);
547
- debugRect(this.pos, size, color, 0, this.angle, hasPhysics);
548
- if (this.parent)
549
- debugRect(this.pos, size.scale(.8), rgb(1,1,1,.5), 0, this.angle);
550
- this.parent && debugLine(this.pos, this.parent.pos, rgb(1,1,1,.5), .5);
551
- }
1
+ /**
2
+ * LittleJS Object System
3
+ * - EngineObject is the base class for all game objects
4
+ * - Handles automatic updating, rendering, physics, and collision
5
+ * - Supports parent-child hierarchies with transform inheritance
6
+ * - 2D physics with velocity, acceleration, damping, and gravity
7
+ * - Collision system with tiles and other objects
8
+ * - Renders sprites from tile sheets with color and rotation
9
+ * - Objects sorted by renderOrder for layered rendering
10
+ */
11
+
12
+ 'use strict';
13
+
14
+ /**
15
+ * LittleJS Object Base Object Class
16
+ * - Top level object class used by the engine
17
+ * - Automatically adds self to object list
18
+ * - Will be updated and rendered each frame
19
+ * - Renders as a sprite from a tilesheet by default
20
+ * - Can have color and additive color applied
21
+ * - 2D Physics and collision system
22
+ * - Sorted by renderOrder
23
+ * - Objects can have children attached
24
+ * - Parents are updated before children, and set child transform
25
+ * - Call destroy() to get rid of objects
26
+ *
27
+ * The physics system used by objects is simple and fast with some caveats...
28
+ * - Collision uses the axis aligned size, the object's rotation angle is only for rendering
29
+ * - Objects are guaranteed to not intersect tile collision from physics
30
+ * - If an object starts or is moved inside tile collision, it will not collide with that tile
31
+ * - Collision for objects can be set to be solid to block other objects
32
+ * - Objects may get pushed into overlapping other solid objects, if so they will push away
33
+ * - A static solid (mass 0) moved by its velocity, like a door or an elevator, pushes objects out of its way
34
+ * - Solid objects are more performance intensive and should be used sparingly
35
+ * @memberof Engine
36
+ * @example
37
+ * // create an engine object, normally you would first extend the class with your own
38
+ * const pos = vec2(2,3);
39
+ * const object = new EngineObject(pos);
40
+ */
41
+ class EngineObject
42
+ {
43
+ /** Create an engine object and adds it to the list of objects
44
+ * @param {Vector2} [pos=vec2()] - World space position of the object
45
+ * @param {Vector2} [size=vec2(1)] - World space size of the object
46
+ * @param {TileInfo} [tileInfo] - Tile info to render object (undefined is untextured)
47
+ * @param {number} [angle] - Angle the object is rotated by
48
+ * @param {Color} [color=WHITE] - Color to apply to tile when rendered
49
+ * @param {number} [renderOrder] - Objects sorted by renderOrder before being rendered
50
+ */
51
+ constructor(pos=vec2(), size=vec2(1), tileInfo, angle=0, color=WHITE, renderOrder=0)
52
+ {
53
+ // check passed in params
54
+ ASSERT(isVector2(pos), 'object pos must be a vec2');
55
+ ASSERT(isVector2(size), 'object size must be a vec2');
56
+ ASSERT(!tileInfo || tileInfo instanceof TileInfo, 'object tileInfo should be a TileInfo or undefined');
57
+ ASSERT(typeof angle === 'number' && isFinite(angle), 'object angle should be a number');
58
+ ASSERT(isColor(color), 'object color should be a valid rgba color');
59
+ ASSERT(typeof renderOrder === 'number', 'object renderOrder should be a number');
60
+
61
+ /** @property {Vector2} - World space position of the object */
62
+ this.pos = pos.copy();
63
+ /** @property {Vector2} - World space width and height of the object */
64
+ this.size = size.copy();
65
+ /** @property {Vector2|undefined} - Size of object used for drawing, uses size if not set
66
+ * @type {Vector2|undefined} */
67
+ this.drawSize = undefined;
68
+ /** @property {TileInfo|undefined} - Tile info to render object (undefined is untextured)
69
+ * @type {TileInfo|undefined} */
70
+ this.tileInfo = tileInfo;
71
+ /** @property {number} - Angle to rotate the object */
72
+ this.angle = angle;
73
+ /** @property {Color} - Color to apply when rendered */
74
+ this.color = color.copy();
75
+ /** @property {Color|undefined} - Additive color to apply when rendered
76
+ * @type {Color|undefined} */
77
+ this.additiveColor = undefined;
78
+ /** @property {Shader|undefined} - Custom shader to render with, undefined for the engine's own
79
+ * @type {Shader|undefined} */
80
+ this.shader = undefined;
81
+ /** @property {boolean} - Does this object draw into the light system's shadow map; false for a floor layer, a background, a pickup */
82
+ this.castShadow = true;
83
+ /** @property {number} - With the light system, how much it lights itself: 0 lit only by the lights, 1 full
84
+ * brightness in its own colors whatever the lights do, between partly; drawn into the lightmap through
85
+ * renderEmissive, as 3D's emissive. Exact for solid pixels; a partly transparent one is self lit by its alpha
86
+ * too, so a half alpha pixel shows at a quarter and a fading emissive sprite fades a little faster */
87
+ this.emissive = 0;
88
+ /** @property {boolean} - Should the rendered tile flip along the y axis. Affects rendering and the local→world transform of attached children (a mirrored parent flips its children's localPos.x and localAngle). Does not affect this object's own physics, collision, or localToWorld/worldToLocal. */
89
+ this.mirror = false;
90
+ /** @property {boolean} - Has object been destroyed? */
91
+ this.destroyed = false;
92
+ this.updatePass = 0; // the engine update pass it was last updated in, so nothing updates twice in one
93
+
94
+ // physical properties
95
+ /** @property {number} - How heavy the object is, static if 0: a static object moves by its velocity but does not
96
+ * collide on its own, the moving ones collide with it */
97
+ this.mass = objectDefaultMass;
98
+ /** @property {number} - Fraction of velocity kept each frame, 1 keeps all of it, 0 stops at once */
99
+ this.damping = objectDefaultDamping;
100
+ /** @property {number} - Fraction of angular velocity kept each frame, 1 keeps all of it, 0 stops at once */
101
+ this.angleDamping = objectDefaultAngleDamping;
102
+ /** @property {number} - How bouncy the object is when colliding (0-1) */
103
+ this.restitution = objectDefaultRestitution;
104
+ /** @property {number} - Fraction of sliding speed kept each frame on the ground, 1 is no friction, 0 stops at
105
+ * once, the more slippery of the object and its ground is used */
106
+ this.friction = objectDefaultFriction;
107
+ /** @property {number} - How much to scale gravity by for this object */
108
+ this.gravityScale = 1;
109
+ /** @property {number} - Objects are sorted by render order */
110
+ this.renderOrder = renderOrder;
111
+ /** @property {Vector2} - Velocity of the object, in world units per frame */
112
+ this.velocity = vec2();
113
+ /** @property {number} - Angular velocity of the object, in radians per frame */
114
+ this.angleVelocity = 0;
115
+ /** @property {number} - Track when object was created */
116
+ this.spawnTime = time;
117
+ /** @property {Array<EngineObject>} - List of children of this object
118
+ * @type {Array<EngineObject>} */
119
+ this.children = [];
120
+ /** @property {boolean} - Limit object speed along x and y axis */
121
+ this.clampSpeed = true;
122
+ /** @property {EngineObject|undefined} - Object we are standing on, if any
123
+ * @type {EngineObject|undefined} */
124
+ this.groundObject = undefined;
125
+
126
+ // parent child system
127
+ /** @property {EngineObject|undefined} - Parent of object if in local space
128
+ * @type {EngineObject|undefined} */
129
+ this.parent = undefined;
130
+ /** @property {Vector2|undefined} - Position relative to the parent, only while attached to one
131
+ * @type {Vector2|undefined} */
132
+ this.localPos = undefined;
133
+ /** @property {number} - Local angle if child */
134
+ this.localAngle = 0;
135
+
136
+ // collision flags
137
+ /** @property {boolean} - Object collides with the level, its tile collision layers
138
+ * @type {boolean} */
139
+ this.collideLevel = false;
140
+ /** @property {boolean} - Object collides with solid objects */
141
+ this.collideSolidObjects = false;
142
+ /** @property {boolean} - Object collides with and blocks other objects */
143
+ this.isSolid = false;
144
+ /** @property {boolean} - Object collides with raycasts */
145
+ this.collideRaycast = false;
146
+
147
+ /** @property {boolean} - Object is skipped by engineObjectsDestroy, for things that outlive a level like a camera
148
+ * - Calling destroy on it still destroys it, and its children go with it either way */
149
+ this.persistent = false;
150
+
151
+ // add to list of objects
152
+ engineObjects.push(this);
153
+ }
154
+
155
+ /** Update the object transform, called automatically by engine even when paused
156
+ * @param {boolean} [updateChildren] - Also update the children's transforms */
157
+ updateTransforms(updateChildren=true)
158
+ {
159
+ const parent = this.parent;
160
+ if (parent)
161
+ {
162
+ // compose with parent transform inline to avoid intermediate vector allocs
163
+ const mirror = parent.getMirrorSign();
164
+ const lp = this.localPos, pp = parent.pos;
165
+ const lx = lp.x*mirror, ly = lp.y, pa = parent.angle;
166
+ if (pa)
167
+ {
168
+ const c = cos(-pa), s = sin(-pa);
169
+ this.pos.set(lx*c - ly*s + pp.x, lx*s + ly*c + pp.y);
170
+ }
171
+ else
172
+ this.pos.set(lx + pp.x, ly + pp.y);
173
+ this.angle = mirror*this.localAngle + pa;
174
+ }
175
+
176
+ // update children
177
+ if (updateChildren)
178
+ for (const child of this.children)
179
+ child.updateTransforms();
180
+ }
181
+
182
+ /** Update the object physics, called automatically by engine once each frame. Can be overridden to stop or change how physics works for an object. */
183
+ updatePhysics()
184
+ {
185
+ // child objects do not have physics
186
+ ASSERT(!this.parent);
187
+
188
+ // bail if a collision callback destroyed us mid-frame
189
+ if (this.destroyed) return;
190
+
191
+ if (this.clampSpeed)
192
+ {
193
+ // limit max speed to prevent missing collisions
194
+ this.velocity.x = clamp(this.velocity.x, -objectMaxSpeed, objectMaxSpeed);
195
+ this.velocity.y = clamp(this.velocity.y, -objectMaxSpeed, objectMaxSpeed);
196
+ }
197
+
198
+ // physics sanity checks
199
+ ASSERT(this.angleDamping >= 0 && this.angleDamping <= 1, 'angleDamping must be 0 to 1, the fraction kept each frame');
200
+ ASSERT(this.damping >= 0 && this.damping <= 1, 'damping must be 0 to 1, the fraction of velocity kept each frame');
201
+
202
+ // apply physics; only the solver needs where the object was, so only then is it copied
203
+ const solve = enablePhysicsSolver && this.mass;
204
+ const oldPos = solve ? this.pos.copy() : undefined;
205
+ this.velocity.x *= this.damping;
206
+ this.velocity.y *= this.damping;
207
+ if (this.mass)
208
+ {
209
+ // apply gravity only if it has mass
210
+ this.velocity.x += gravity.x * this.gravityScale;
211
+ this.velocity.y += gravity.y * this.gravityScale;
212
+ }
213
+ this.pos.x += this.velocity.x;
214
+ this.pos.y += this.velocity.y;
215
+ this.angle += this.angleVelocity *= this.angleDamping;
216
+
217
+ // don't do collision for static objects or if solver disabled
218
+ if (!solve) return;
219
+
220
+ // which way is down for this object, a negative gravityScale falls up and lands on ceilings
221
+ const gravityY = this.gravityScale < 0 ? -gravity.y : gravity.y;
222
+ const wasFalling = this.velocity.y < 0 && gravityY < 0 || this.velocity.y > 0 && gravityY > 0;
223
+ if (this.groundObject)
224
+ {
225
+ // apply friction in local space of ground object
226
+ const friction = max(this.friction, this.groundObject.friction);
227
+ const groundSpeed = this.groundObject.velocity.x;
228
+ this.velocity.x = groundSpeed + (this.velocity.x - groundSpeed) * friction;
229
+ this.groundObject = undefined;
230
+ }
231
+
232
+ // an object with no width or height has no box to push out of, or to be pushed out of
233
+ if (this.collideSolidObjects && this.size.x && this.size.y)
234
+ {
235
+ // check collisions against solid objects
236
+ const epsilon = .001; // necessary to push slightly outside of the collision
237
+ for (const o of engineObjectsCollideStaticLast)
238
+ {
239
+ // skip destroyed, child objects, self collision, or objects with no box
240
+ if (o.destroyed || o.parent || o === this || !o.size.x || !o.size.y) continue;
241
+
242
+ // non solid objects don't collide with each other
243
+ if (!this.isSolid && !o.isSolid) continue;
244
+
245
+ // check collision
246
+ if (!this.isOverlappingObject(o)) continue;
247
+
248
+ // each moving object checks its own contacts, so a pair the other one already asked about this frame
249
+ // is not asked twice: left overlapping, ignored or only nudged apart it is skipped, and one both said
250
+ // to resolve, pushed back together since, is resolved again
251
+ const answer = engineObjectsCollidePairAnswer(o, this);
252
+ if (answer === false) continue;
253
+ if (!answer)
254
+ {
255
+ // notify objects of collision and check if should be resolved
256
+ const collide1 = this.collideWithObject(o);
257
+ const collide2 = o.collideWithObject(this);
258
+ if (!collide1 || !collide2)
259
+ {
260
+ engineObjectsCollidePairAdd(this, o);
261
+ continue;
262
+ }
263
+ }
264
+
265
+ const wasOverlapping = isOverlapping(oldPos, this.size, o.pos, o.size);
266
+ if (wasOverlapping && (!o.mass || o.groundObject))
267
+ {
268
+ // a static solid that moved into it, like a door or an elevator, pushes it out the shortest way
269
+ // at once and carries it along, it would only drift out slowly and the solid would pass through;
270
+ // an object standing on something counts as fixed too, so a stack on an elevator rides together;
271
+ // it bounces off relative to the mover, a paddle moved by setting pos bounces a ball as a wall does
272
+ const push = collideBoxBox(this.pos, this.size, o.pos, o.size);
273
+ if (push)
274
+ {
275
+ this.pos.x += push.x + sign(push.x) * epsilon;
276
+ this.pos.y += push.y + sign(push.y) * epsilon;
277
+ const restitution = max(this.restitution, o.restitution);
278
+ if (push.x)
279
+ {
280
+ const v = this.velocity.x - o.velocity.x;
281
+ if (v * push.x < 0) // moving into it
282
+ this.velocity.x = o.velocity.x - v * restitution;
283
+ }
284
+ else
285
+ {
286
+ const v = this.velocity.y - o.velocity.y;
287
+ if (v * push.y < 0) // moving into it
288
+ this.velocity.y = o.velocity.y - v * restitution;
289
+ if (push.y * gravityY < 0) // pushed up against gravity, it stands on it
290
+ this.groundObject = o;
291
+ }
292
+ }
293
+ engineObjectsCollidePairAdd(this, o);
294
+
295
+ debugPhysics && debugOverlap(this.pos, this.size, o.pos, o.size, '#f00', undefined, false);
296
+ continue;
297
+ }
298
+ if (wasOverlapping)
299
+ {
300
+ // if already was touching, try to push away
301
+ const deltaPos = oldPos.subtract(o.pos);
302
+ const length = deltaPos.length();
303
+ const pushAwayAccel = .001;
304
+ const velocity = length < .001 ? vec2(0, pushAwayAccel) : deltaPos.scale(pushAwayAccel/length);
305
+ this.velocity = this.velocity.add(velocity);
306
+ if (o.mass) // push away other object if not fixed
307
+ o.velocity = o.velocity.subtract(velocity);
308
+ engineObjectsCollidePairAdd(this, o);
309
+
310
+ debugPhysics && debugOverlap(this.pos, this.size, o.pos, o.size, '#f00', undefined, false);
311
+ continue;
312
+ }
313
+
314
+ // check for collision
315
+ const sizeBoth = this.size.add(o.size);
316
+ // prefer to push up if small delta, up away from this object's own gravity
317
+ const smallStepUp = (gravityY > 0 ? o.pos.y - oldPos.y : oldPos.y - o.pos.y)*2 > sizeBoth.y - abs(gravityY);
318
+ const isBlockedX = abs(oldPos.y - o.pos.y)*2 < sizeBoth.y;
319
+ const isBlockedY = abs(oldPos.x - o.pos.x)*2 < sizeBoth.x;
320
+ const restitution = max(this.restitution, o.restitution);
321
+
322
+ if (smallStepUp || isBlockedY || !isBlockedX) // resolve y collision
323
+ {
324
+ // push outside object collision
325
+ this.pos.y = o.pos.y + (sizeBoth.y/2 + epsilon) * sign(oldPos.y - o.pos.y);
326
+ if ((o.groundObject && wasFalling) || !o.mass)
327
+ {
328
+ // set ground object if landed on something
329
+ if (wasFalling)
330
+ this.groundObject = o;
331
+
332
+ // bounce if other object is fixed or grounded, relative to it so a rider keeps up with a
333
+ // platform moving down instead of landing on it again every few frames
334
+ this.velocity.y = o.velocity.y - (this.velocity.y - o.velocity.y) * restitution;
335
+ }
336
+ else // o has mass here, the other branch already handled the massless case
337
+ {
338
+ // inelastic collision
339
+ const inelastic = (this.mass * this.velocity.y + o.mass * o.velocity.y) / (this.mass + o.mass);
340
+
341
+ // elastic collision
342
+ const elastic0 = this.velocity.y * (this.mass - o.mass) / (this.mass + o.mass)
343
+ + o.velocity.y * 2 * o.mass / (this.mass + o.mass);
344
+ const elastic1 = o.velocity.y * (o.mass - this.mass) / (this.mass + o.mass)
345
+ + this.velocity.y * 2 * this.mass / (this.mass + o.mass);
346
+
347
+ // lerp between elastic or inelastic based on restitution
348
+ this.velocity.y = lerp(inelastic, elastic0, restitution);
349
+ o.velocity.y = lerp(inelastic, elastic1, restitution);
350
+ }
351
+ }
352
+ if (!smallStepUp && isBlockedX) // resolve x collision
353
+ {
354
+ // push outside collision
355
+ this.pos.x = o.pos.x + (sizeBoth.x/2 + epsilon) * sign(oldPos.x - o.pos.x);
356
+ if (o.mass)
357
+ {
358
+ // inelastic collision
359
+ const inelastic = (this.mass * this.velocity.x + o.mass * o.velocity.x) / (this.mass + o.mass);
360
+
361
+ // elastic collision
362
+ const elastic0 = this.velocity.x * (this.mass - o.mass) / (this.mass + o.mass)
363
+ + o.velocity.x * 2 * o.mass / (this.mass + o.mass);
364
+ const elastic1 = o.velocity.x * (o.mass - this.mass) / (this.mass + o.mass)
365
+ + this.velocity.x * 2 * this.mass / (this.mass + o.mass);
366
+
367
+ // lerp between elastic or inelastic based on restitution
368
+ this.velocity.x = lerp(inelastic, elastic0, restitution);
369
+ o.velocity.x = lerp(inelastic, elastic1, restitution);
370
+ }
371
+ else // bounce if other object is fixed, relative to it as a landing is
372
+ this.velocity.x = o.velocity.x - (this.velocity.x - o.velocity.x) * restitution;
373
+ }
374
+ engineObjectsCollidePairAdd(this, o, true);
375
+ debugPhysics && debugOverlap(this.pos, this.size, o.pos, o.size, '#f0f', undefined, false);
376
+ }
377
+ }
378
+ if (this.collideLevel)
379
+ {
380
+ // check collision against tiles
381
+ const hitLayer = tileCollisionTest(this.pos, this.size, this);
382
+ if (hitLayer)
383
+ {
384
+ // if already was stuck in collision, don't do anything
385
+ // this should not happen unless something starts in collision
386
+ if (!tileCollisionTest(oldPos, this.size, this))
387
+ {
388
+ // test which side we bounced off (or both if a corner)
389
+ const isBlockedX = tileCollisionTest(vec2(this.pos.x, oldPos.y), this.size, this);
390
+ const isBlockedY = tileCollisionTest(vec2(oldPos.x, this.pos.y), this.size, this);
391
+ const restitution = max(this.restitution, hitLayer.restitution);
392
+ if (isBlockedX)
393
+ {
394
+ // a ledge caught less than maxMove below its top lifts the object onto it instead of stopping it,
395
+ // down off a ceiling ledge when gravity points up; zero gravity counts as down
396
+ const epsilon = 1e-3;
397
+ const maxMove = .1;
398
+ const y = gravityY > 0 ?
399
+ ceil( oldPos.y+this.size.y/2-1) - this.size.y/2 - epsilon :
400
+ floor(oldPos.y-this.size.y/2+1) + this.size.y/2 + epsilon;
401
+ if (abs(y - this.pos.y) < maxMove && !tileCollisionTest(vec2(this.pos.x, y), this.size, this))
402
+ {
403
+ this.pos.y = y;
404
+ debugPhysics && debugRect(this.pos, this.size, '#ff0', 0, 0, false, false);
405
+ return;
406
+ }
407
+
408
+ // move to previous X position and bounce
409
+ this.pos.x = oldPos.x;
410
+ this.velocity.x *= -restitution;
411
+ }
412
+ if (isBlockedY || !isBlockedX)
413
+ {
414
+ if (wasFalling)
415
+ {
416
+ // adjust position to slightly away from nearest tile
417
+ // this prevents gap between object and ground
418
+ const epsilon = .0001;
419
+ const offset = this.size.y/2 + epsilon;
420
+ // rounded in the layer's space as its collision test is, or a bottom a hair below a
421
+ // grid line would round to the row under it, inside the floor, and fall through
422
+ const layerY = hitLayer.pos.y;
423
+ this.pos.y = layerY + (gravityY < 0 ?
424
+ floor(oldPos.y - layerY - this.size.y/2) + offset :
425
+ ceil( oldPos.y - layerY + this.size.y/2) - offset);
426
+
427
+ // set ground object for tile collision
428
+ this.groundObject = hitLayer;
429
+ }
430
+ else
431
+ {
432
+ // move to previous Y position
433
+ this.pos.y = oldPos.y;
434
+ this.groundObject = undefined;
435
+ }
436
+ // bounce velocity
437
+ this.velocity.y *= -restitution;
438
+ }
439
+ debugPhysics && debugRect(this.pos, this.size, '#f00', 0, 0, false, false);
440
+ }
441
+ }
442
+ }
443
+ }
444
+
445
+ /** Update the object, called automatically by engine once each frame. Does nothing by default. */
446
+ update() {}
447
+
448
+ /** Render the object, draws a tile by default, automatically called each frame, sorted by renderOrder */
449
+ render()
450
+ {
451
+ // default object render
452
+ drawTile(this.pos, this.drawSize || this.size, this.tileInfo, this.color, this.angle, this.mirror, this.additiveColor, glEnable, false);
453
+ }
454
+
455
+ /** Optional hook called during the light system plugin's lightmap pass to draw this object's lightmap contribution. Does nothing by default. */
456
+ renderLight() {}
457
+
458
+ /** Draw this object into the light system's shadow map, called during its shadow pass when castShadow is set.
459
+ * Calls render() by default so the object casts its own shape; override to cast a different one, like a blob at a character's feet so its body stays lit;
460
+ * screen space WebGL draws in render() are skipped during the pass */
461
+ renderShadow() { this.render(); }
462
+
463
+ /** Draw this object's shape into the light system's lightmap, called during its light pass when emissive is above
464
+ * 0; what it draws shows in its own colors that much brighter. Calls render() by default so the whole object
465
+ * glows; override to glow a part, like a robot's eyes */
466
+ renderEmissive() { this.render(); }
467
+
468
+ /** Destroy this object, destroy its children, detach its parent, and mark it for removal
469
+ * @param {boolean} [immediate] - true removes attached effects like particle emitters at once, false lets them finish first */
470
+ destroy(immediate=false)
471
+ {
472
+ if (this.destroyed) return;
473
+
474
+ // disconnect from parent and destroy children
475
+ this.destroyed = true;
476
+ this.parent?.removeChild(this);
477
+ for (const child of this.children)
478
+ {
479
+ child.parent = undefined;
480
+ child.destroy(immediate);
481
+ }
482
+ }
483
+
484
+ /** Convert from local space to world space
485
+ * @param {Vector2} pos - local space point */
486
+ localToWorld(pos) { return this.pos.add(pos.rotate(this.angle)); }
487
+
488
+ /** Convert from world space to local space
489
+ * @param {Vector2} pos - world space point */
490
+ worldToLocal(pos) { return pos.subtract(this.pos).rotate(-this.angle); }
491
+
492
+ /** Convert from local space to world space for a vector (rotation only)
493
+ * @param {Vector2} vec - local space vector */
494
+ localToWorldVector(vec) { return vec.rotate(this.angle); }
495
+
496
+ /** Convert from world space to local space for a vector (rotation only)
497
+ * @param {Vector2} vec - world space vector */
498
+ worldToLocalVector(vec) { return vec.rotate(-this.angle); }
499
+
500
+ /** Called to check if a tile collision should be resolved. Return true for physics to resolve the collision or false to ignore and resolve it manually.
501
+ * - Called for each solid tile the physics tests, which can be several times a frame for the same tile, and for
502
+ * positions it only tries, so keep it free of side effects or guard them to once a frame
503
+ * - this.pos has already moved, so a check on where it came from, like a one way platform, needs the position
504
+ * saved in update, as the platformer example does
505
+ * @param {number} tileData - the value of the tile at the position
506
+ * @param {Vector2} pos - the tile's bottom left corner in world space
507
+ * @return {boolean} - true if the collision should be resolved by modifying it's position and velocity */
508
+ collideWithTile(tileData, pos) { return tileData > 0; }
509
+
510
+ /** Called by the engine to check if an object collision should be resolved. Return true for physics to resolve the collision or false to ignore and resolve it manually.
511
+ * - Both objects of a touching pair are asked once a frame, whichever order they update in; an object that
512
+ * destroys itself here is gone at the end of the frame and is still asked about the pairs left this frame, so a
513
+ * bullet that should hit one thing checks its own destroyed flag first
514
+ * @param {EngineObject} object - the object to test against
515
+ * @param {Vector3} [push] - what it would take to move this object clear, a Vector3 from the 3D plugin, undefined in 2D
516
+ * @return {boolean} - true if the collision should be resolved by modifying it's position and velocity
517
+ */
518
+ collideWithObject(object, push) { return true; }
519
+
520
+ /** Get this object's up vector
521
+ * @param {number} [scale] - length of the vector
522
+ * @return {Vector2} */
523
+ getUp(scale=1) { return vec2().setAngle(this.angle, scale); }
524
+
525
+ /** Get this object's right vector
526
+ * @param {number} [scale] - length of the vector
527
+ * @return {Vector2} */
528
+ getRight(scale=1) { return vec2().setAngle(this.angle+PI/2, scale); }
529
+
530
+ /** How long since the object was created
531
+ * @return {number} */
532
+ getAliveTime() { return time - this.spawnTime; }
533
+
534
+ /** Get the speed of this object
535
+ * @return {number} */
536
+ getSpeed() { return this.velocity.length(); }
537
+
538
+ /** Apply acceleration to this object (adjust velocity, not affected by mass)
539
+ * - Does nothing on a static object (mass 0), set its velocity instead
540
+ * @param {Vector2} acceleration */
541
+ applyAcceleration(acceleration)
542
+ { if (this.mass) this.velocity = this.velocity.add(acceleration); }
543
+
544
+ /** Apply angular acceleration to this object
545
+ * - Does nothing on a static object (mass 0), set its angleVelocity instead
546
+ * @param {number} acceleration */
547
+ applyAngularAcceleration(acceleration)
548
+ { if (this.mass) this.angleVelocity += acceleration; }
549
+
550
+ /** Apply force to this object (adjust velocity, affected by mass)
551
+ * - Does nothing on a static object (mass 0), set its velocity instead
552
+ * @param {Vector2} force */
553
+ applyForce(force)
554
+ { if (this.mass) this.applyAcceleration(force.scale(1/this.mass)); }
555
+
556
+ /** Get the direction of the mirror
557
+ * @return {number} -1 if this.mirror is true, or 1 if not mirrored */
558
+ getMirrorSign() { return this.mirror ? -1 : 1; }
559
+
560
+ /** Attaches a child to this with a local transform, returns child for chaining
561
+ * @param {EngineObject} child
562
+ * @param {Vector2} [localPos=vec2()]
563
+ * @param {number} [localAngle]
564
+ * @return {EngineObject} The child object added */
565
+ addChild(child, localPos=vec2(), localAngle=0)
566
+ {
567
+ ASSERT(!this.destroyed, 'cannot add child to destroyed object');
568
+ if (this.destroyed) return child;
569
+ ASSERT(!child.parent && !this.children.includes(child), 'child already has a parent, removeChild it first or use attach');
570
+ ASSERT(child instanceof EngineObject, 'child must be an EngineObject');
571
+ ASSERT(!child.destroyed, 'cannot add a destroyed child');
572
+ for (let p = /** @type {EngineObject} */ (this); p; p = p.parent)
573
+ ASSERT(p !== child, 'cannot add an object as a child of itself or of its own child');
574
+ this.children.push(child);
575
+ child.parent = this;
576
+ child.localPos = localPos.copy();
577
+ child.localAngle = localAngle;
578
+ child.updateTransforms();
579
+ return child;
580
+ }
581
+
582
+ /** Attaches a child to this without moving it: the local transform is worked out from where the child is now,
583
+ * where addChild takes one; a child of something else is moved over, returns child for chaining
584
+ * @param {EngineObject} child
585
+ * @return {EngineObject} The child object attached */
586
+ attach(child)
587
+ {
588
+ ASSERT(child instanceof EngineObject, 'child must be an EngineObject');
589
+ ASSERT(child !== this, 'cannot attach self');
590
+ child.parent?.removeChild(child);
591
+ // the local values that updateTransforms turns back into the child's current pos and angle
592
+ const mirror = this.getMirrorSign(), local = this.worldToLocal(child.pos);
593
+ local.x *= mirror;
594
+ return this.addChild(child, local, mirror * (child.angle - this.angle));
595
+ }
596
+
597
+ /** Removes a child from this one, it stays where it is in the world
598
+ * @param {EngineObject} child */
599
+ removeChild(child)
600
+ {
601
+ ASSERT(child.parent === this && this.children.includes(child));
602
+ const i = this.children.indexOf(child);
603
+ if (i < 0) return; // not a child of this one, release has no assert
604
+ this.children.splice(i, 1);
605
+ child.parent = child.localPos = undefined;
606
+ }
607
+
608
+ /** Check if this object's box overlaps another object's box
609
+ * @param {EngineObject} object
610
+ * @return {boolean} */
611
+ isOverlappingObject(object)
612
+ { return this.isOverlapping(object.pos, object.size); }
613
+
614
+ /** Check if overlapping a point or aligned bounding box
615
+ * @param {Vector2} pos - Center of box
616
+ * @param {Vector2} [size=vec2()] - Size of box, uses a point if undefined
617
+ * @return {boolean} */
618
+ isOverlapping(pos, size=vec2())
619
+ { return isOverlapping(this.pos, this.size, pos, size); }
620
+
621
+ /** Set how this object collides
622
+ * @param {boolean} [collideSolidObjects] - Does it collide with solid objects?
623
+ * @param {boolean} [isSolid] - Does it collide with and block other objects? (expensive in large numbers)
624
+ * @param {boolean} [collideLevel] - Does it collide with the level, its tile collision layers?
625
+ * @param {boolean} [collideRaycast] - Does it collide with raycasts? */
626
+ setCollision(collideSolidObjects=true, isSolid=true, collideLevel=true, collideRaycast=true)
627
+ {
628
+ ASSERT(collideSolidObjects || !isSolid, 'solid objects must be set to collide');
629
+
630
+ this.collideSolidObjects = collideSolidObjects;
631
+ this.isSolid = isSolid;
632
+ this.collideLevel = collideLevel;
633
+ this.collideRaycast = collideRaycast;
634
+ }
635
+
636
+ /** @deprecated since 1.20, use collideLevel
637
+ * @type {boolean} */
638
+ get collideTiles() { return this.collideLevel; }
639
+ set collideTiles(collide) { this.collideLevel = collide; }
640
+
641
+ /** Returns string containing info about this object for debugging
642
+ * @return {string} */
643
+ toString()
644
+ {
645
+ let text = 'type = ' + this.constructor.name;
646
+ if (this.pos.x || this.pos.y)
647
+ text += '\npos = ' + this.pos;
648
+ if (this.velocity.x || this.velocity.y)
649
+ text += '\nvelocity = ' + this.velocity;
650
+ if (this.size.x || this.size.y)
651
+ text += '\nsize = ' + this.size;
652
+ if (this.angle)
653
+ text += '\nangle = ' + this.angle.toFixed(3);
654
+ text += '\ncolor = ' + this.color;
655
+ return text;
656
+ }
657
+
658
+ /** Render debug info for this object */
659
+ renderDebugInfo()
660
+ {
661
+ if (!debug) return;
662
+
663
+ // check if there is anything to show
664
+ const hasPhysics = this.collideLevel || this.collideSolidObjects || this.isSolid;
665
+ if (!hasPhysics && !this.parent) return;
666
+
667
+ // show object info for debugging
668
+ const size = vec2(max(this.size.x, .2), max(this.size.y, .2));
669
+ const color = rgb(this.collideLevel?1:0, this.collideSolidObjects?1:0, this.isSolid?1:0, .5);
670
+ debugRect(this.pos, size, color, 0, hasPhysics ? 0 : this.angle, hasPhysics, false); // collision ignores the angle
671
+ if (this.parent)
672
+ debugRect(this.pos, size.scale(.8), rgb(1,1,1,.5), 0, this.angle, false, false);
673
+ this.parent && debugLine(this.pos, this.parent.pos, rgb(1,1,1,.5), .5, 0, false);
674
+ }
552
675
  }