littlejsengine 1.18.4 → 1.18.8

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 (176) hide show
  1. package/COPYRIGHT.txt +38 -0
  2. package/FAQ.md +633 -0
  3. package/README.md +19 -1
  4. package/dist/littlejs.d.ts +354 -55
  5. package/dist/littlejs.esm.js +1531 -489
  6. package/dist/littlejs.esm.min.js +1 -1
  7. package/dist/littlejs.js +1499 -476
  8. package/dist/littlejs.min.js +1 -1
  9. package/dist/littlejs.release.js +1493 -470
  10. package/package.json +8 -1
  11. package/plugins/box2d.js +32 -7
  12. package/{src/engineMedals.js → plugins/medalSystem.js} +248 -196
  13. package/plugins/pathFinder.js +758 -0
  14. package/plugins/pluginExport.js +19 -0
  15. package/plugins/{tween.js → tweenSystem.js} +7 -7
  16. package/plugins/uiSystem.js +186 -25
  17. package/src/engine.js +2 -141
  18. package/src/engineAudio.js +3 -3
  19. package/src/engineBuild.mjs +4 -2
  20. package/src/engineDebug.js +7 -7
  21. package/src/engineDraw.js +26 -8
  22. package/src/engineExport.js +13 -13
  23. package/src/engineInput.js +8 -8
  24. package/src/engineLogo.js +146 -0
  25. package/src/engineMath.js +15 -6
  26. package/src/engineObject.js +11 -5
  27. package/src/engineParticles.js +6 -3
  28. package/src/engineRelease.js +1 -1
  29. package/src/engineSettings.js +0 -47
  30. package/src/engineUtilities.js +13 -8
  31. package/src/engineWebGL.js +34 -7
  32. package/src/jsconfig.json +3 -1
  33. package/.github/workflows/test.yml +0 -17
  34. package/AI.md +0 -173
  35. package/CLAUDE.md +0 -1
  36. package/examples/box2d/game.js +0 -192
  37. package/examples/box2d/gameObjects.js +0 -564
  38. package/examples/box2d/index.html +0 -9
  39. package/examples/box2d/scenes.js +0 -194
  40. package/examples/box2d/tiles.png +0 -0
  41. package/examples/breakout/game.js +0 -175
  42. package/examples/breakout/gameObjects.js +0 -147
  43. package/examples/breakout/index.html +0 -8
  44. package/examples/breakout/tiles.png +0 -0
  45. package/examples/breakoutTutorial/README.md +0 -521
  46. package/examples/breakoutTutorial/game.js +0 -191
  47. package/examples/breakoutTutorial/images/1.png +0 -0
  48. package/examples/breakoutTutorial/images/10.png +0 -0
  49. package/examples/breakoutTutorial/images/11.png +0 -0
  50. package/examples/breakoutTutorial/images/2.png +0 -0
  51. package/examples/breakoutTutorial/images/3.png +0 -0
  52. package/examples/breakoutTutorial/images/4.png +0 -0
  53. package/examples/breakoutTutorial/images/5.png +0 -0
  54. package/examples/breakoutTutorial/images/6.png +0 -0
  55. package/examples/breakoutTutorial/images/7.png +0 -0
  56. package/examples/breakoutTutorial/images/8.png +0 -0
  57. package/examples/breakoutTutorial/images/9.png +0 -0
  58. package/examples/breakoutTutorial/index.html +0 -8
  59. package/examples/electron/build.mjs +0 -127
  60. package/examples/electron/electron.js +0 -35
  61. package/examples/electron/game.js +0 -54
  62. package/examples/electron/index.html +0 -13
  63. package/examples/electron/package.json +0 -5
  64. package/examples/electron/tiles.png +0 -0
  65. package/examples/empty/game.js +0 -51
  66. package/examples/empty/index.html +0 -5
  67. package/examples/empty/tiles.png +0 -0
  68. package/examples/favicon.png +0 -0
  69. package/examples/games.jpg +0 -0
  70. package/examples/htmlMenu/game.js +0 -82
  71. package/examples/htmlMenu/index.html +0 -45
  72. package/examples/htmlMenu/tiles.png +0 -0
  73. package/examples/index.html +0 -62
  74. package/examples/logo.png +0 -0
  75. package/examples/logo2.png +0 -0
  76. package/examples/module/build.mjs +0 -124
  77. package/examples/module/game.js +0 -132
  78. package/examples/module/index.html +0 -10
  79. package/examples/module/tiles.png +0 -0
  80. package/examples/particles/index.html +0 -426
  81. package/examples/particles/tiles.png +0 -0
  82. package/examples/platformer/data/gameLevelData.tmx +0 -143
  83. package/examples/platformer/data/gameLevelData.tsx +0 -4
  84. package/examples/platformer/game.js +0 -147
  85. package/examples/platformer/gameCharacter.js +0 -309
  86. package/examples/platformer/gameEffects.js +0 -278
  87. package/examples/platformer/gameLevel.js +0 -205
  88. package/examples/platformer/gameLevelData.json +0 -171
  89. package/examples/platformer/gameObjects.js +0 -378
  90. package/examples/platformer/gamePlayer.js +0 -35
  91. package/examples/platformer/index.html +0 -9
  92. package/examples/platformer/tiles.png +0 -0
  93. package/examples/platformer/tilesLevel.png +0 -0
  94. package/examples/puzzle/game.js +0 -331
  95. package/examples/puzzle/index.html +0 -8
  96. package/examples/puzzle/tiles.png +0 -0
  97. package/examples/screenshot.jpg +0 -0
  98. package/examples/shorts/animation.js +0 -18
  99. package/examples/shorts/base.html +0 -54
  100. package/examples/shorts/blending.js +0 -14
  101. package/examples/shorts/box2d.js +0 -51
  102. package/examples/shorts/box2dCar.js +0 -59
  103. package/examples/shorts/box2dPool.js +0 -107
  104. package/examples/shorts/box2dTileLayer.js +0 -48
  105. package/examples/shorts/cameraDrag.js +0 -22
  106. package/examples/shorts/clock.js +0 -21
  107. package/examples/shorts/colors.js +0 -25
  108. package/examples/shorts/debugDraw.js +0 -37
  109. package/examples/shorts/empty.js +0 -30
  110. package/examples/shorts/flappyGame.js +0 -55
  111. package/examples/shorts/fontImage.js +0 -17
  112. package/examples/shorts/fps.js +0 -90
  113. package/examples/shorts/helloWorld.js +0 -11
  114. package/examples/shorts/hillGlideGame.js +0 -63
  115. package/examples/shorts/input.js +0 -64
  116. package/examples/shorts/landerGame.js +0 -57
  117. package/examples/shorts/maze.js +0 -48
  118. package/examples/shorts/medals.js +0 -51
  119. package/examples/shorts/music.js +0 -78
  120. package/examples/shorts/musicPlayer.js +0 -137
  121. package/examples/shorts/nineSlice.js +0 -40
  122. package/examples/shorts/parallax.js +0 -72
  123. package/examples/shorts/particles.js +0 -28
  124. package/examples/shorts/piano.js +0 -44
  125. package/examples/shorts/platformer.js +0 -45
  126. package/examples/shorts/pongGame.js +0 -41
  127. package/examples/shorts/postProcess.js +0 -62
  128. package/examples/shorts/sequencer.js +0 -124
  129. package/examples/shorts/shader.js +0 -29
  130. package/examples/shorts/shapes.js +0 -21
  131. package/examples/shorts/slidingPuzzle.js +0 -52
  132. package/examples/shorts/song.mp3 +0 -0
  133. package/examples/shorts/sound.js +0 -36
  134. package/examples/shorts/spaceGame.js +0 -58
  135. package/examples/shorts/spriteAtlas.js +0 -31
  136. package/examples/shorts/starfield.js +0 -15
  137. package/examples/shorts/texture.js +0 -16
  138. package/examples/shorts/textureWrapped.js +0 -12
  139. package/examples/shorts/tileLayer.js +0 -48
  140. package/examples/shorts/tileRaycast.js +0 -39
  141. package/examples/shorts/tiles.png +0 -0
  142. package/examples/shorts/tiltedView.js +0 -63
  143. package/examples/shorts/timers.js +0 -53
  144. package/examples/shorts/topDown.js +0 -38
  145. package/examples/shorts/tween.js +0 -24
  146. package/examples/shorts/uiSystem.js +0 -61
  147. package/examples/shorts/video.webm +0 -0
  148. package/examples/shorts/videoPlayer.js +0 -34
  149. package/examples/shorts.js +0 -743
  150. package/examples/starter/build.bat +0 -7
  151. package/examples/starter/build.mjs +0 -126
  152. package/examples/starter/game.js +0 -137
  153. package/examples/starter/index.html +0 -35
  154. package/examples/starter/tiles.png +0 -0
  155. package/examples/stress/index.html +0 -173
  156. package/examples/style.css +0 -150
  157. package/examples/tweenSystem/game.js +0 -171
  158. package/examples/tweenSystem/index.html +0 -10
  159. package/examples/tweenSystem/tiles.png +0 -0
  160. package/examples/typescript/build.mjs +0 -60
  161. package/examples/typescript/game.js +0 -100
  162. package/examples/typescript/game.ts +0 -132
  163. package/examples/typescript/index.html +0 -10
  164. package/examples/typescript/tiles.png +0 -0
  165. package/examples/typescript/tsconfig.json +0 -17
  166. package/examples/uiSystem/game.js +0 -139
  167. package/examples/uiSystem/index.html +0 -10
  168. package/examples/uiSystem/tiles.png +0 -0
  169. package/jsconfig.json +0 -12
  170. package/plugins/desktop.ini +0 -2
  171. package/reference.md +0 -448
  172. package/test/math.test.mjs +0 -774
  173. package/test/setup.mjs +0 -22
  174. package/test/smoke.test.mjs +0 -274
  175. package/test/tween.test.mjs +0 -576
  176. package/test/util.test.mjs +0 -80
package/COPYRIGHT.txt ADDED
@@ -0,0 +1,38 @@
1
+ LittleJS Notices and Third-Party Licenses
2
+ =========================================
3
+
4
+ This repository is licensed under the MIT License. See the file LICENSE.
5
+
6
+ This file collects copyright notices and third-party license texts for
7
+ software included with or used by this repository. If you redistribute
8
+ LittleJS with third-party components, keep the relevant notices below.
9
+
10
+ -------------------------------------------------------------------------------
11
+
12
+ LittleJS Engine License
13
+
14
+ Copyright (c) 2021 Frank Force
15
+ http://www.frankforce.com
16
+ Licensed under the MIT License. See LICENSE.
17
+
18
+ -------------------------------------------------------------------------------
19
+
20
+ Box2D License
21
+
22
+ Copyright (c) 2006-2013 Erin Catto http://www.gphysics.com
23
+
24
+ This software is provided 'as-is', without any express or implied
25
+ warranty. In no event will the authors be held liable for any damages
26
+ arising from the use of this software.
27
+
28
+ Permission is granted to anyone to use this software for any purpose,
29
+ including commercial applications, and to alter it and redistribute it
30
+ freely, subject to the following restrictions:
31
+
32
+ 1. The origin of this software must not be misrepresented; you must not
33
+ claim that you wrote the original software. If you use this software
34
+ in a product, an acknowledgment in the product documentation would be
35
+ appreciated but is not required.
36
+ 2. Altered source versions must be plainly marked as such, and must not be
37
+ misrepresented as being the original software.
38
+ 3. This notice may not be removed or altered from any source distribution.
package/FAQ.md ADDED
@@ -0,0 +1,633 @@
1
+ # LittleJS Frequently Asked Questions
2
+
3
+ Welcome to the LittleJS FAQ!
4
+ This document addresses common questions and issues to help developers get started and troubleshoot their projects.
5
+ If you don't find an answer here, feel free to ask the community or check the documentation.
6
+
7
+ Getting Started
8
+ - [What is LittleJS, and how is it different from other JavaScript game engines?](#what-is-littlejs-and-how-is-it-different-from-other-javascript-game-engines)
9
+ - [How do I set up a basic LittleJS project?](#how-do-i-set-up-a-basic-littlejs-project)
10
+ - [How do I use LittleJS as an ES module?](#how-do-i-use-littlejs-as-an-es-module)
11
+ - [How do I use LittleJS with TypeScript?](#how-do-i-use-littlejs-with-typescript)
12
+ - [Why do I see a blank screen when I run my game?](#why-do-i-see-a-blank-screen-when-i-run-my-game)
13
+ - [Do I need a local server to run LittleJS games, and how do I set one up?](#do-i-need-a-local-server-to-run-littlejs-games-and-how-do-i-set-one-up)
14
+ - [How does the camera and world coordinate systems work?](#how-does-the-camera-and-world-coordinate-systems-work)
15
+ - [How do I use Vite with LittleJS?](#how-do-i-use-vite-with-littlejs)
16
+ - [How do I use Box2D with Vite?](#how-do-i-use-box2d-with-vite)
17
+ - [How do I build and publish my game?](#how-do-i-build-and-publish-my-game)
18
+
19
+ Graphics and Sound
20
+ - [How do I load and add images to my game?](#how-do-i-load-and-add-images-to-my-game)
21
+ - [What is the tile function and how do tile indexes work?](#what-is-the-tile-function-and-how-do-tile-indexes-work)
22
+ - [Can I add and switch between multiple sprites for a game object?](#can-i-add-and-switch-between-multiple-sprites-for-a-game-object)
23
+ - [There are thin lines around my sprites sometimes, how can I fix that?](#there-are-thin-lines-around-my-sprites-sometimes-how-can-i-fix-that)
24
+ - [How do I handle animations in LittleJS?](#how-do-i-handle-animations-in-littlejs)
25
+ - [How do I control the camera in LittleJS?](#how-do-i-control-the-camera-in-littlejs)
26
+ - [How do I use post-processing shaders?](#how-do-i-use-post-processing-shaders)
27
+ - [How do I play sounds in LittleJS?](#how-do-i-play-sounds-in-littlejs)
28
+ - [If I load several images, how do I control which is used?](#if-i-load-several-images-how-do-i-control-which-is-used)
29
+ - [How can I check if an object is on screen?](#how-can-i-check-if-an-object-is-on-screen)
30
+
31
+ Gameplay and Programming
32
+ - [How do I add keyboard or mouse input to my game?](#how-do-i-add-keyboard-or-mouse-input-to-my-game)
33
+ - [How does touch input work on mobile?](#how-does-touch-input-work-on-mobile)
34
+ - [How do I create and update game objects?](#how-do-i-create-and-update-game-objects)
35
+ - [How can I load a 2D level map?](#how-can-i-load-a-2d-level-map)
36
+ - [Can I use physics with LittleJS?](#can-i-use-physics-with-littlejs)
37
+ - [How do I add particle effects to my game?](#how-do-i-add-particle-effects-to-my-game)
38
+ - [How do I save and load game state?](#how-do-i-save-and-load-game-state)
39
+ - [How do I use the medals (achievements) system?](#how-do-i-use-the-medals-achievements-system)
40
+
41
+ Debugging and Development
42
+ - [How do I debug my game in LittleJS?](#how-do-i-debug-my-game-in-littlejs)
43
+
44
+ ---
45
+
46
+ ## Getting Started
47
+ ### What is LittleJS, and how is it different from other JavaScript game engines?
48
+
49
+ LittleJS is a lightweight, high-performance JavaScript game engine designed for simplicity and speed.
50
+ It offers a hybrid rendering system that combines the advantages of WebGL and 2D Canvas.
51
+ Unlike larger, feature-heavy engines, LittleJS focuses on 2D games and providing a comprehensive set of simple, easy to use features.
52
+ LittleJS is perfect for developers who want a minimal yet powerful engine to bring their 2D game ideas to life without the complexity of larger frameworks.
53
+
54
+ ### How do I set up a basic LittleJS project?
55
+
56
+ Download the LittleJS repository via GitHub or npm.
57
+ Include one of the LittleJS builds from the dist folder.
58
+ Several examples are included for you to build on.
59
+ The most basic example is just an empty project.
60
+
61
+ [Empty Example HTML file:](https://github.com/KilledByAPixel/LittleJS/blob/main/examples/empty/index.html)
62
+ ```html
63
+ <!DOCTYPE html><head>
64
+ <title>LittleJS Hello World Demo</title>
65
+ <meta charset=utf-8>
66
+ </head><body>
67
+
68
+ <script src=../../dist/littlejs.js></script>
69
+ <script src=game.js></script>
70
+ ```
71
+
72
+ [Empty Example JavaScript file:](https://github.com/KilledByAPixel/LittleJS/blob/main/examples/empty/game.js)
73
+ ```javascript
74
+ /*
75
+ Little JS Hello World Demo
76
+ - Just prints "Hello World!"
77
+ - A good starting point for new projects
78
+ */
79
+
80
+ 'use strict';
81
+
82
+ ///////////////////////////////////////////////////////////////////////////////
83
+ function gameInit()
84
+ {
85
+ // called once after the engine starts up
86
+ // setup the game
87
+ }
88
+
89
+ ///////////////////////////////////////////////////////////////////////////////
90
+ function gameUpdate()
91
+ {
92
+ // called every frame at 60 frames per second
93
+ // handle input and update the game state
94
+ }
95
+
96
+ ///////////////////////////////////////////////////////////////////////////////
97
+ function gameUpdatePost()
98
+ {
99
+ // called after physics and objects are updated
100
+ // setup camera and prepare for render
101
+ }
102
+
103
+ ///////////////////////////////////////////////////////////////////////////////
104
+ function gameRender()
105
+ {
106
+ // called before objects are rendered
107
+ // draw any background effects that appear behind objects
108
+ }
109
+
110
+ ///////////////////////////////////////////////////////////////////////////////
111
+ function gameRenderPost()
112
+ {
113
+ // called after objects are rendered
114
+ // draw effects or hud that appear above all objects
115
+ drawTextScreen('Hello World!', mainCanvasSize.scale(.5), 80);
116
+ }
117
+
118
+ ///////////////////////////////////////////////////////////////////////////////
119
+ // Startup LittleJS Engine
120
+ engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost, ['tiles.png']);
121
+ ```
122
+
123
+ This is the simplest setup — two files served by a local web server. If you'd rather start from a bundler-based project with hot reload, see [How do I use Vite with LittleJS?](#how-do-i-use-vite-with-littlejs) for the official Vite starter template.
124
+
125
+ ### How do I use LittleJS as an ES module?
126
+
127
+ If you're using a bundler (Vite, Rollup, webpack, etc.) or just want to use native ES modules, install via npm and import what you need:
128
+
129
+ ```
130
+ npm install littlejsengine
131
+ ```
132
+
133
+ ```javascript
134
+ import { engineInit, drawText, vec2 } from 'littlejsengine';
135
+
136
+ function gameInit() {}
137
+ function gameUpdate() {}
138
+ function gameUpdatePost() {}
139
+ function gameRender() {}
140
+ function gameRenderPost() {
141
+ drawText('Hello!', vec2(0,0), 4);
142
+ }
143
+
144
+ engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost, ['tiles.png']);
145
+ ```
146
+
147
+ You can also import everything under a namespace:
148
+
149
+ ```javascript
150
+ import * as LJS from 'littlejsengine';
151
+ LJS.drawText('Hello!', LJS.vec2(0,0), 4);
152
+ ```
153
+
154
+ For a working example, see [examples/module/](examples/module/). That example imports from a relative path (`'../../dist/littlejs.esm.js'`) since it runs straight out of the repo without `npm install` — once you've installed the package, replace that with `'littlejsengine'` as shown above. The Vite section below shows the full bundler-based setup.
155
+
156
+ ### How do I use LittleJS with TypeScript?
157
+
158
+ LittleJS ships with type definitions in `dist/littlejs.d.ts`, which the npm package wires up automatically. Install via npm and you get type checking with no extra setup:
159
+
160
+ ```
161
+ npm install littlejsengine
162
+ ```
163
+
164
+ ```typescript
165
+ import { engineInit, drawText, vec2 } from 'littlejsengine';
166
+
167
+ function gameInit(): void {}
168
+ function gameUpdate(): void {}
169
+ function gameUpdatePost(): void {}
170
+ function gameRender(): void {}
171
+ function gameRenderPost(): void {
172
+ drawText('Hello!', vec2(0,0), 4);
173
+ }
174
+
175
+ engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost, ['tiles.png']);
176
+ ```
177
+
178
+ See [examples/typescript/](examples/typescript/) for a complete TypeScript project with `tsconfig.json`. You can also adapt the Vite starter — Vite supports TypeScript out of the box, just rename `src/main.js` to `src/main.ts` and update the `index.html` script reference.
179
+
180
+ ### Why do I see a blank screen when I run my game?
181
+
182
+ If you are seeing a blank screen, first try opening the dev tools console (F12 in most browsers).
183
+ This will show you any errors that occur and allows stepping through code to help debug.
184
+ A common issue is the image data failing to load with a message like "The image element contains cross-origin data, and may not be loaded."
185
+ This is probably because the game was loaded directly without using a web server!
186
+
187
+ ### Do I need a local server to run LittleJS games, and how do I set one up?
188
+
189
+ Yes, this is a necessary step because web browsers just have protection from loading local files which includes images.
190
+ So any JavaScript projects that load images like games must be opened from a local web server.
191
+ Don't panic though, it's very easy to fix!
192
+
193
+ If you are using [Visual Studio Code](https://code.visualstudio.com/) there is a [Live Preview Extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode.live-server) that will handle this for you automatically.
194
+
195
+ Another option is to setup a simple local web server like [http-server](https://www.npmjs.com/package/http-server) via npm.
196
+
197
+ ### How does the camera and world coordinate systems work?
198
+
199
+ LittleJS drawing functions are all handled in world coordinates by default.
200
+ The conversion from world to screen is determined by the camera position and scale as well as the canvas size in pixels.
201
+ Camera scale determines how many screen pixels equals 1 world unit while the cameraPosition is the offset in world units.
202
+ There is also a function you can use called getCameraSize() to get the viewable camera window in world coordinates.
203
+
204
+ ### How do I use Vite with LittleJS?
205
+
206
+ There is an official [Vite](https://vite.dev) starter template in `examples/vite-starter`. The fastest way to start a new project from it is with [degit](https://github.com/Rich-Harris/degit):
207
+
208
+ ```
209
+ npx degit KilledByAPixel/LittleJS/examples/vite-starter my-game
210
+ cd my-game
211
+ npm install
212
+ npm run dev
213
+ ```
214
+
215
+ Vite will print a local URL (usually `http://localhost:5173/`) — open it and you should see the LittleJS logo tile and "LittleJS + Vite" text.
216
+
217
+ Key things the template sets up for you:
218
+ - `base: './'` in `vite.config.js` so the build works on GitHub Pages, itch.io, and other subdirectory hosts without further config.
219
+ - Assets in `public/` (like `tiles.png`) are served at the site root in dev and copied to the build output, so `engineInit(..., ['tiles.png'])` works in both modes without a separate import.
220
+ - A `public/.nojekyll` marker so GitHub Pages serves Vite's `_`-prefixed chunk files correctly.
221
+ - A full page reload on save instead of partial HMR, since LittleJS has engine-level global state (canvas, WebGL, input listeners, the RAF loop) that doesn't survive a module hot swap. The relevant line in `src/main.js` is `if (import.meta.hot) import.meta.hot.accept(() => location.reload())`.
222
+
223
+ Requires Node 20.19+ or 22.12+ (Vite 7 requirement). Other community projects like [Michael Haynie's LittleJS Jam project](https://github.com/michael-dean-haynie/littlejs-game-jam-2024) are good real-world references for more elaborate Vite setups.
224
+
225
+ ### How do I use Box2D with Vite?
226
+
227
+ Box2D ships as two separate files in the npm package: `box2d.wasm.js` (the Emscripten loader, ~300KB) and `box2d.wasm.wasm` (the binary, ~167KB). Both live in `node_modules/littlejsengine/dist/`.
228
+
229
+ The catch: `box2d.wasm.js` fetches the `.wasm` from **its own script directory** using `document.currentScript.src`. That means the two files have to be served side by side, and `box2d.wasm.js` has to be loaded as a classic `<script>` tag — not a module, no `defer`, no `async` — so `document.currentScript` resolves correctly.
230
+
231
+ **To add Box2D to the Vite starter:**
232
+
233
+ 1. Copy both files into `public/`:
234
+
235
+ ```
236
+ public/
237
+ box2d.wasm.js
238
+ box2d.wasm.wasm
239
+ ```
240
+
241
+ 2. Add a script tag to `index.html` *before* your module script:
242
+
243
+ ```html
244
+ <script src=./box2d.wasm.js></script>
245
+ <script src=./src/main.js type=module></script>
246
+ ```
247
+
248
+ Vite may print an informational warning during build that the classic script can't be bundled without `type=module` — this is expected and harmless. The classic-script form is exactly what's needed so Emscripten can read `document.currentScript.src` to locate the `.wasm` file.
249
+
250
+ 3. Await `box2dInit()` in `main.js` before `engineInit`:
251
+
252
+ ```javascript
253
+ import { box2dInit, engineInit } from 'littlejsengine';
254
+
255
+ await box2dInit();
256
+ engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost, ['tiles.png']);
257
+ ```
258
+
259
+ To avoid copying the files by hand on every fresh install, add a `postinstall` script to `package.json`:
260
+
261
+ ```json
262
+ "scripts": {
263
+ "postinstall": "node -e \"['box2d.wasm.js','box2d.wasm.wasm'].forEach(f=>require('fs').copyFileSync('node_modules/littlejsengine/dist/'+f,'public/'+f))\""
264
+ }
265
+ ```
266
+
267
+ Then `npm install` keeps `public/box2d.wasm.*` in sync with whatever version of `littlejsengine` you have installed. Add them to `.gitignore` if you don't want the binaries in your repo.
268
+
269
+ ### How do I build and publish my game?
270
+
271
+ It depends on how your project is set up:
272
+
273
+ **Plain script-tag projects** (like `examples/starter`) are already deployable as-is. For production, swap the debug bundle for a release build to strip asserts and shrink the file:
274
+
275
+ ```html
276
+ <!-- During development -->
277
+ <script src=dist/littlejs.js></script>
278
+
279
+ <!-- For production: stripped asserts, smaller -->
280
+ <script src=dist/littlejs.release.js></script>
281
+
282
+ <!-- Smallest: minified release -->
283
+ <script src=dist/littlejs.min.js></script>
284
+ ```
285
+
286
+ Then zip up your game folder for itch.io or push to GitHub Pages.
287
+
288
+ **Vite / module projects** — run `npm run build` and deploy the output `dist/` folder.
289
+
290
+ **For GitHub Pages**, use relative asset paths (the Vite starter sets `base: './'` in `vite.config.js` for this), and include an empty `.nojekyll` file in your output so files starting with `_` aren't ignored by Jekyll.
291
+
292
+ **For itch.io**, zip your build output and upload as an HTML5 game. Tick "This file will be played in the browser" in the upload settings.
293
+
294
+ **For size coding competitions** like js13kGames, see the [js13k branch](https://github.com/KilledByAPixel/LittleJS/tree/js13k) which provides a build that fits in 7KB zipped.
295
+
296
+ ---
297
+
298
+ ## Graphics and Sound
299
+
300
+ ### How do I load and add images to my game?
301
+
302
+ First you need to load an image file. For LittleJS this is typically done on startup via a parameter to engineInit that is a list of images to load. The engine will ensure that all images are loaded before starting. Most modern devices support textures up to 4096x4096 or larger, though some older mobile devices cap out at 2048x2048 — keep that lower limit in mind if you need broad compatibility. Most games only need one texture, but you can load as many as you need.
303
+
304
+ ```javascript
305
+ engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost, ['tiles.png']);
306
+ ```
307
+
308
+ LittleJS works best when your tile sheet is broken up into grids of tiles because the rendering system can be batched up. To draw a tile from a source image you can call drawTile and pass in TileInfo object. Another common approach is to create an EngineObject and set its tileInfo, it will automatically be rendered.
309
+
310
+ ```javascript
311
+ drawTile(vec2(21,5), vec2(4.5), tile(3,128));
312
+ ```
313
+
314
+ Once loaded, the underlying images are available via `textureInfos[0].image`, `textureInfos[1].image`, etc. This is useful for tasks like reading pixel data to generate a level — see [examples/module/game.js](examples/module/game.js) for an example that reads tile data directly from an image.
315
+
316
+ ### What is the tile function and how do tile indexes work?
317
+
318
+ The `tile` function returns a `TileInfo` object pointing at a region of a loaded image, ready to pass to `drawTile`, an `EngineObject`, a particle emitter, etc.
319
+
320
+ ```javascript
321
+ tile(2) // index 2 at the default tile size (16x16)
322
+ tile(5, 8) // index 5 at 8x8 tile size
323
+ tile(1, 16, 3) // index 1 of size 16 on texture 3 (multi-image projects)
324
+ tile(vec2(4,8), vec2(30,10)) // explicit (x,y) tile position with a 30x10 region
325
+ ```
326
+
327
+ When you pass a numeric index, the engine multiplies it by the tile size to get pixel coordinates inside the texture. Indexes count left-to-right, top-to-bottom — so for a 16x16 tile sheet, `tile(0, 16)` is the top-left tile, `tile(1, 16)` is the one to its right, `tile(8, 16)` wraps to the next row if your sheet is 8 tiles wide, etc.
328
+
329
+ The full signature is `tile(index, size, texture, padding, bleed)`:
330
+ - `texture` — which loaded image to read from (index into the array you passed to `engineInit`, default 0)
331
+ - `padding` — pixels of padding between tiles in the sheet, if you laid them out with space around each
332
+ - `bleed` — shrink the sampled region slightly to avoid edge bleeding (see the tile-bleed entry above)
333
+
334
+ ### Can I add and switch between multiple sprites for a game object?
335
+
336
+ Yes — there are several ways depending on what you need.
337
+
338
+ **Set the sprite when creating the object** via the `tileInfo` parameter on `EngineObject`:
339
+
340
+ ```javascript
341
+ class Player extends EngineObject {
342
+ constructor(pos) {
343
+ super(pos, vec2(1), tile(0, 16)); // start with tile index 0
344
+ }
345
+ }
346
+ ```
347
+
348
+ **Swap the sprite at runtime** by assigning a new `TileInfo`:
349
+
350
+ ```javascript
351
+ this.tileInfo = tile(3, 16); // now showing tile index 3
352
+ ```
353
+
354
+ **For frame-based animation**, store a base `TileInfo` and use `.frame(n)` to offset along the row:
355
+
356
+ ```javascript
357
+ const baseSprite = tile(2, 16);
358
+ this.tileInfo = baseSprite.frame(animationFrame); // 0, 1, 2... walks to the right
359
+ ```
360
+
361
+ **To draw an arbitrary sprite without an object**, call `drawTile` directly:
362
+
363
+ ```javascript
364
+ drawTile(pos, vec2(1), tile(5, 16));
365
+ ```
366
+
367
+ ### There are thin lines around my sprites sometimes, how can I fix that?
368
+
369
+ That's called tile bleeding — pixels from one tile blend into a neighboring tile when sampling at sub-pixel positions. Two ways to fix it:
370
+
371
+ 1. Call `setTileDefaultBleed(.5)` (or pass a `bleed` parameter to `tile()` / the `TileInfo` constructor). This shrinks each tile slightly when sampling. A value around `.5` usually eliminates the issue with no noticeable visual difference. Smaller values like `.1` are sometimes enough.
372
+
373
+ 2. Add 1 pixel of padding around each sprite in your spritesheet, then pass that padding to `tile(index, size, texture, padding)` so the engine accounts for it.
374
+
375
+ ### How do I handle animations in LittleJS?
376
+
377
+ Use the `TileInfo.frame(n)` method to offset along a row of animation frames on your sprite sheet. Lay out each animation's frames left-to-right next to each other on the sheet, then index into them from a base sprite:
378
+
379
+ ```javascript
380
+ // store the base sprite (the first frame of the animation)
381
+ const playerSprite = tile(0, 16);
382
+
383
+ // inside update(), advance the frame based on time
384
+ const animationFrame = Math.floor(time * 10) % 4; // 4-frame loop at 10 FPS
385
+ this.tileInfo = playerSprite.frame(animationFrame);
386
+ ```
387
+
388
+ `time` is a global updated by the engine each frame (in seconds). The `% 4` keeps the index inside the 4 frames you actually drew on the sheet — adjust to match your animation length.
389
+
390
+ ### How do I control the camera in LittleJS?
391
+
392
+ LittleJS uses a world space rendering system, so objects can move independently of the camera.
393
+ The camera is easy to control using cameraPosition and cameraScale, which indicate the world space position and how many pixels is equivalent to one world unit.
394
+ The default cameraScale is 32 while the default cameraPosition is just the origin.
395
+ It is also possible to draw using screen space pixel coordinates by passing in true as the screenSpace parameter to most drawing functions.
396
+
397
+ ```javascript
398
+ setCameraPos(vec2(22,5)); // move camera to world position (22,5)
399
+ setCameraScale(20); // zoom camera to 20 pixels per world unit
400
+ ```
401
+
402
+ ### How do I use post-processing shaders?
403
+
404
+ LittleJS supports Shadertoy-style fragment shaders as a final pass on the rendered output via the post-process plugin. Create the plugin with your shader source before `engineInit`:
405
+
406
+ ```javascript
407
+ const shader = `
408
+ void mainImage(out vec4 c, vec2 p) {
409
+ vec2 uv = p / iResolution.xy;
410
+ c = texture(iChannel0, uv);
411
+ c.rgb *= 1.0 - distance(uv, vec2(0.5)) * 0.7; // vignette
412
+ }`;
413
+
414
+ new PostProcessPlugin(shader);
415
+ engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost);
416
+ ```
417
+
418
+ The shader gets these uniforms automatically:
419
+
420
+ - `iChannel0` (`sampler2D`) — the rendered game frame
421
+ - `iResolution` (`vec3`) — canvas width, height, and `1`
422
+ - `iTime` (`float`) — seconds since engine start
423
+
424
+ The constructor has two optional positional arguments after the shader source:
425
+
426
+ ```javascript
427
+ new PostProcessPlugin(shader, includeMainCanvas, feedbackTexture);
428
+ ```
429
+
430
+ - `includeMainCanvas=true` composites the Canvas2D layer (where some debug and text rendering goes) onto the WebGL canvas before the shader runs. Pass `true` if your post-process effect should apply to *everything* on screen, not just the WebGL-rendered objects.
431
+ - `feedbackTexture=true` makes the previous frame available as `iChannel0` for effects like motion trails or feedback loops. Mutually exclusive with `includeMainCanvas`.
432
+
433
+ See [plugins/postProcess.js](plugins/postProcess.js) and the [Breakout example](https://killedbyapixel.github.io/LittleJS/examples/breakout/) for working post-process effects.
434
+
435
+ ### How do I play sounds in LittleJS?
436
+
437
+ Sounds can either be generated on startup using ZzFX or loaded from a wave or mp3 file.
438
+ [ZzFX sounds can be created using the sound designer app.](https://killedbyapixel.github.io/ZzFX/)
439
+ Once loaded sounds can be played by calling Sound.play with some parameters to control how it is played.
440
+
441
+ ```javascript
442
+ const sound_click = new Sound([1,.5]); // create a ZzFX sound
443
+ const sound_jump = new Sound('jump.mp3'); // load an mp3 sound
444
+ sound_click.play(pos, volume, pitch); // play a sound
445
+ ```
446
+
447
+ ### If I load several images, how do I control which is used?
448
+
449
+ Pass multiple image paths to `engineInit` and select between them with the third argument to `tile()` (the `texture` index):
450
+
451
+ ```javascript
452
+ // load two images
453
+ engineInit(..., ['tiles.png', 'background.png']);
454
+
455
+ // later, draw a tile from each
456
+ const fgTile = tile(0, 16); // texture 0 → tiles.png
457
+ const bgTile = tile(0, 16, 1); // texture 1 → background.png
458
+ ```
459
+
460
+ The `texture` argument defaults to `0`, so single-image projects can ignore it. One thing to keep in mind for large games: switching between textures forces WebGL to flush its current render batch, so frequently alternating between textures within a single frame can hurt performance. Group draws by texture where you can.
461
+
462
+ ### How can I check if an object is on screen?
463
+
464
+ You can use the `isOverlapping` function to check the object against the camera's viewable window. For culling you might want to enlarge the object size slightly to account for attached objects or rotation — I usually do `this.size.scale(2)`.
465
+
466
+ ```javascript
467
+ if (!isOverlapping(this.pos, this.size, cameraPos, getCameraSize()))
468
+ return;
469
+ ```
470
+
471
+ `getCameraSize()` returns the viewable window in world units (canvas pixel size divided by `cameraScale`).
472
+
473
+ ---
474
+
475
+ ## Gameplay and Programming
476
+
477
+ ### How do I add keyboard or mouse input to my game?
478
+
479
+ LittleJS provides input handling functions for keyboard, mouse, and gamepads. Touch input is also routed to the mouse. There are functions for isDown, wasPressed, and wasReleased. Input can only be checked during the update and should not be called from render functions.
480
+
481
+ ```javascript
482
+ if (keyIsDown('ArrowLeft')) // Left arrow key
483
+ obj.pos.x -= 5;
484
+ if (mouseWasReleased(0)) // Left mouse button
485
+ console.log('Mouse clicked at:', mousePos);
486
+ if (gamepadWasPressed(0)) // Gamepad button 0
487
+ console.log('Gamepad pressed, stick is:', gamepadStick(0));
488
+ ```
489
+
490
+ Keyboard keys are identified by `KeyboardEvent.code` strings (e.g. `'KeyA'`, `'Space'`, `'ArrowUp'`, `'Enter'`). See the [MDN code reference](https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_code_values) for the full list.
491
+
492
+ ### How does touch input work on mobile?
493
+
494
+ Touch input is routed to the mouse functions automatically — `mouseIsDown(0)`, `mouseWasPressed(0)`, and `mousePos` all work with a finger tap on the canvas. Games written for mouse usually work on mobile without code changes.
495
+
496
+ For games that need movement and multiple buttons, enable the built-in on-screen gamepad:
497
+
498
+ ```javascript
499
+ setTouchGamepadEnable(true);
500
+ ```
501
+
502
+ Once enabled, an analog stick and face buttons appear on touch devices, and the regular gamepad input functions (`gamepadIsDown`, `gamepadStick`) work normally — so the same code can drive both a physical gamepad and the touch overlay. Customization helpers like `setTouchGamepadSize`, `setTouchGamepadAnalog`, `setTouchGamepadButtonCount`, and `setTouchGamepadAlpha` let you tune the appearance.
503
+
504
+ You can also branch behavior on `isTouchDevice` if you need to detect touch hardware explicitly.
505
+
506
+ ### How do I create and update game objects?
507
+
508
+ LittleJS can be used as an object oriented system by extending the base class [EngineObject](https://github.com/KilledByAPixel/LittleJS/blob/main/src/engineObject.js) with your own. This lightweight class provides many useful features including physics, collision, parent/child system, and sorted rendering. These objects are added to the global list of objects where they will automatically be updated and rendered until destroyed.
509
+
510
+ Here is a template you can use to make objects that behave however you want. See the examples for a complete demonstration.
511
+
512
+ ```javascript
513
+ class MyObject extends EngineObject
514
+ {
515
+ constructor(pos, size, tileInfo)
516
+ {
517
+ super(pos, size, tileInfo);
518
+ // setup object
519
+ }
520
+
521
+ update()
522
+ {
523
+ // update object physics and position
524
+ super.update();
525
+ }
526
+
527
+ render()
528
+ {
529
+ // draw object as a sprite
530
+ super.render();
531
+ }
532
+ }
533
+
534
+ // spawn one of those objects
535
+ const object = new MyObject(pos, size, tileInfo);
536
+ ```
537
+
538
+ Common things you'll do on an `EngineObject`:
539
+
540
+ - `this.setCollision()` — opt in to tile collision and object-object collision
541
+ - `this.tileInfo = tile(7, 16)` — swap the sprite at runtime
542
+ - `this.velocity = vec2(.1, 0)` — physics is applied automatically each frame
543
+ - `this.gravityScale = 0` — disable gravity for this object (e.g. UI or floating objects)
544
+ - `this.destroy()` — remove from the world (calls cleanup on children too)
545
+
546
+ ### How can I load a 2D level map?
547
+
548
+ There are two parts that work together to make 2D level maps in LittleJS.
549
+ The tileCollision system is an array of values that correspond to each tile in the map.
550
+ The built in physics system can resolve collisions against this tile map very quickly.
551
+ For the visual side of things, there is a class called TileLayer which can be used in conjunction with tileCollision.
552
+ The TileLayer system works by pre-rendering the entire level to a texture so it can be drawn extremely fast each frame.
553
+ It is also possible to have multiple TileLayers for foreground and background layers.
554
+ [The platformer example shows a basic example of how to load data that was exported from an external editor.](https://killedbyapixel.github.io/LittleJS/examples/platformer/)
555
+
556
+ ### Can I use physics with LittleJS?
557
+
558
+ Yes! LittleJS comes with a robust game physics system included and [also a plugin using Box2D.](https://killedbyapixel.github.io/LittleJS/examples/box2d/)
559
+ The platformer example includes a character object class that can be used as a starting point for advanced platforming physics.
560
+
561
+ ### How do I add particle effects to my game?
562
+
563
+ [There is a particle system designer that is useful for experimenting with particle designs.](https://killedbyapixel.github.io/LittleJS/examples/particles/)
564
+
565
+ You can create a particle system in code using the ParticleEmitter object.
566
+
567
+ ```javascript
568
+ // fire particle system
569
+ new ParticleEmitter(
570
+ pos, 0, // pos, angle
571
+ 1, .1, 100, PI, // emitSize, emitTime, emitRate, emitCone
572
+ undefined, // tileInfo (undefined = untextured)
573
+ rgb(1,.5,.1), rgb(1,.1,.1), // colorStartA, colorStartB
574
+ rgb(1,.5,.1,0), rgb(1,.1,.1,0), // colorEndA, colorEndB
575
+ .7, .8, .2, .2, .05, // time, sizeStart, sizeEnd, speed, angleSpeed
576
+ .9, 1, -.2, PI, .05, // damp, angleDamp, gravity, particleCone, fade
577
+ .5, 0, 1, 0, 1e9 // randomness, collide, additive, colorLinear, renderOrder
578
+ );
579
+ ```
580
+
581
+ ### How do I save and load game state?
582
+
583
+ LittleJS has built-in helpers for localStorage-backed save data — no need to roll your own JSON serialization:
584
+
585
+ ```javascript
586
+ // Read save data, falling back to defaults if nothing is saved yet
587
+ const saveData = readSaveData('MyGame', { highScore: 0, level: 1 });
588
+
589
+ // Write save data
590
+ writeSaveData('MyGame', { highScore: 99999, level: 5 });
591
+ ```
592
+
593
+ The `saveName` should be unique per game so multiple LittleJS games on the same host don't collide. The data object must be JSON-serializable (no functions, no circular references). Under the hood these are thin wrappers around `localStorage` + `JSON.stringify` / `JSON.parse`.
594
+
595
+ ### How do I use the medals (achievements) system?
596
+
597
+ LittleJS includes a medals plugin for tracking unlockable achievements with toast notifications:
598
+
599
+ ```javascript
600
+ // Create medals — each needs a unique id, optional emoji icon
601
+ const medal_firstWin = new Medal(0, 'First Win', 'Win your first match', '🏆');
602
+ const medal_perfect = new Medal(1, 'Perfect Score', 'Score 100%', '⭐');
603
+
604
+ // Initialize medals — saveName persists unlocks to localStorage
605
+ medalsInit('MyGame');
606
+
607
+ // Unlock a medal (shows notification, persists across sessions)
608
+ medal_firstWin.unlock();
609
+ ```
610
+
611
+ You can pass an image URL as the fifth argument to `Medal` instead of an emoji icon. The `saveName` you pass to `medalsInit` is used to track which medals have been unlocked in localStorage, so unlocks persist across sessions.
612
+
613
+ The plugin also supports [Newgrounds](https://www.newgrounds.com) integration via `newgrounds.io` for hosted leaderboards and cloud-synced achievements. See [plugins/medalSystem.js](plugins/medalSystem.js) for details.
614
+
615
+ ---
616
+
617
+ ## Debugging and Development
618
+
619
+ ### How do I debug my game in LittleJS?
620
+
621
+ In addition to your browser's built in developer mode, LittleJS has its own debug view.
622
+ Press the Esc key to show the debug menu. From here there are several options that can be accessed via the number keys.
623
+
624
+ You can also press + or - to adjust game speed to help with debugging, or just for fun!
625
+
626
+ ---
627
+
628
+ ## Contribute to the FAQ
629
+ If you have additional questions or think something should be added to this FAQ, please open an issue or pull request on the [LittleJS GitHub repository](https://github.com/KilledByAPixel/LittleJS).
630
+
631
+ ---
632
+
633
+ Happy coding with LittleJS! 🎮🚂💨