LittleJS 1.30.0

Engine

LittleJS - The Tiny Fast JavaScript Game Engine MIT License - Copyright 2021 Frank Force

Engine Features

  • Object oriented system with EngineObject base class
  • Automatic object lifecycle (update, physics, collision, rendering)
  • Engine helper classes: Vector2, Color, Timer, RandomGenerator
  • Hybrid rendering with WebGL batching and Canvas2D fallback
  • Audio system with wave, mp3, or ZzFX sound effects
  • Input system with keyboard, mouse, gamepad, and touch support
  • Tile layer rendering and collision detection
  • Particle effect system with emitters
  • Medal/achievement system with local storage
  • Comprehensive debug tools and visualizations
  • Fixed 60 FPS timestep with configurable time scale
  • Raycast and spatial query utilities
  • Plugin system for extending engine functionality
  • Start with engineInit() and provide your game callbacks

Classes

Functions

Members

Constants

Typedefs

Functions

engineAddLoad(promise) → Promise<any>engine.js:396

Add something the game loads to what startup waits for: while engineInit and gameInit run, the game loop starts once it is done, and the loading screen counts it; images from loadTexture and sounds from files are added on their own, and a load that fails counts as done; after startup it does nothing

promise Promise<any>
Returns
  • The same promise
async function gameInit() { level = await engineAddLoad(fetchJSON('level.json')); }
engineAddPlugin(update, render, glContextLost, glContextRestored, preRender, updatePost)engine.js:372

Add a new update function for a plugin

  • update runs on every fixed tick, paused and timeScale 0 included; a plugin that simulates should skip those
update PluginCallback optional
render PluginCallback optional
glContextLost PluginCallback optional
glContextRestored PluginCallback optional
preRender PluginCallback optional

Called after the canvas is cleared and before gameRender

updatePost PluginCallback optional

Called after the objects update each tick, before gameUpdatePost, paused included, for what follows an object, like a camera

engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost, imageSources, rootElement) → Promise<void>asyncengine.js:480

Startup LittleJS engine with your callback functions

gameInit GameInitCallback optional

Called once after the engine starts up, can be async for loading

gameUpdate GameCallback optional

Called every frame before objects are updated (60fps), use for game logic

gameUpdatePost GameCallback optional

Called after physics and objects are updated, even when paused, use for UI updates

gameRender GameCallback optional

Called before objects are rendered, use for drawing backgrounds/world elements

gameRenderPost GameCallback optional

Called after objects are rendered, use for drawing UI/overlays

imageSources Array<string>|string optional, default []

List of image file paths to preload (e.g., ['player.png', 'tiles.png']), or one path

rootElement HTMLElement optional

Root DOM element to attach canvas to, defaults to document.body; it is styled for a game (no scroll bars or selection, touch-action none) where its own inline style does not say otherwise, and the canvas centers inside it, but the canvas is still sized from the window, so set canvasFixedSize or canvasMaxSize to fit a smaller element

Returns
  • Done when the images have loaded and gameInit has run
// Basic engine startup
engineInit(
  ()=> { LOG('Game initialized!'); },  // gameInit
  ()=> { updateGameLogic(); },         // gameUpdate
  ()=> { updateUI(); },                // gameUpdatePost
  ()=> { drawBackground(); },          // gameRender
  ()=> { drawHUD(); },                 // gameRenderPost
  ['tiles.png', 'tilesLevel.png']       // images to load
);
engineObjectsCallback(pos, size, callbackFunction, objects, testCenters)engine.js:1167

Triggers a callback for each object within a given area, objects destroyed this frame left out

pos Vector2 optional

Center of test area, or undefined for all objects

size Vector2|number optional

Diameter of a circle if a number, full size of a rectangle if a Vector2

callbackFunction ObjectCallbackFunction optional

Calls this function on every object that passes the test, needed (marked optional only because the area before it is)

objects Array<EngineObject> optional, default engineObjects

List of objects to check

testCenters boolean optional, default false

Test only each object's center, see engineObjectsCollect

engineObjectsCollect(pos, size, objects, testCenters) → Array<EngineObject>engine.js:1120

Collects all object within a given area

  • An object is collected when its box overlaps the area, or with testCenters when its center is inside it
  • Objects destroyed this frame are left out, they are only in the list until the frame ends
pos Vector2 optional

Center of test area, or undefined for all objects

size Vector2|number optional

Diameter of a circle if a number, full size of a rectangle if a Vector2, left out or 0 the objects that overlap the point at pos

objects Array<EngineObject> optional, default engineObjects

List of objects to check

testCenters boolean optional, default false

Test only each object's center, a little faster, and ignores object sizes

Returns
  • List of collected objects
engineObjectsDestroy(immediate)engine.js:1100

Destroy and remove all objects

  • This can be used to clear out all objects when restarting a level
  • Objects with the persistent flag set are left alone, for things that outlive a level
  • Objects can override their destroy function to do cleanup or stick around
immediate boolean optional, default true

true removes attached effects like particle emitters at once, false lets them finish first

engineObjectsRaycast(start, end, objects) → Array<EngineObject>engine.js:1181

Return a list of objects intersecting a ray, objects destroyed this frame left out

  • Only objects with collideRaycast set are hit, which setCollision turns on
start Vector2
end Vector2
objects Array<EngineObject> optional, default engineObjects

List of objects to check

Returns
  • List of objects hit
engineObjectsUpdate()engine.js:976

Update each engine object and remove destroyed objects; time and frame are advanced by the engine loop, not here

  • Can be called manually if objects need to be updated outside of main loop
engineStep(frames)engine.js:958

Advance the engine by a number of frames Requires setEngineManualStep(true), before engineInit or while running; it stops early if an update turns it off Respects paused exactly as the normal update loop does Does nothing until the promise engineInit returns has resolved, which waits for the images, and the sounds gameInit made, to load; a test hook steps from that promise's then

frames number optional, default 1

frames of 1/60 of a second to advance, max 36000; timeScale sets how many fixed updates they run, as in the normal loop, one each at timeScale 1

setHeadlessMode(true);
setEngineManualStep(true);
await engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost);
engineStep(600); // 600 updates of 1/60 second; the first is at time 0, so time is then 599/60, with
                 // setEngineVariableStep(true) the first is at 1/60 and time is 600/60
getPaused() → booleanengine.js:89

Get if game is paused

setPaused(isPaused)engine.js:94

Set if game is paused

isPaused boolean optional, default true

Members

averageFPS : numberengine.js:103

Display frames per second, the browser's animation frames whether or not one drew, smoothed over about a third of a second, in release builds too

engineObjects : Array<EngineObject>engine.js:53

Array containing all engine objects

engineObjectsCollide : Array<EngineObject>engine.js:58

Array with only objects set to collide with other objects this frame (for optimization)

frame : numberengine.js:66

Current update frame, used to calculate time

paused : boolean default falseengine.js:84

Is the game paused? Causes time and objects to not be updated

time : numberengine.js:73

Current engine time since start in seconds

  • Below 20 FPS it falls behind the clock, since a frame catches up at most 50 ms of updates, so a timer in real seconds, one that must keep up on a slow device, goes by timeReal
timeDelta : number default 1/60engine.js:48

How many seconds the update covers: 1/60 with the fixed time step, or with engineVariableStep the time of the display frame it runs on, times timeScale; while paused it keeps the last update's

timeReal : numberengine.js:78

Actual clock time since start in seconds (not affected by pause, timescale, or frame rate clamping; the debug speed keys scale it in debug builds)

Constants

engineInit.promises : Array<Promise<any>>engine.js:753
engineInit.splash : Promise<void>engine.js:766
engineName : string default LittleJSengine.js:29

Name of engine

engineVersion : string default 1.30.0engine.js:35

Version of engine

frameRate : number default 60engine.js:41

Frames per second to update

Typedefs

GameCallback() → voidengine.js:451
GameInitCallback() → void|Promise<void>engine.js:440
LoadingScreenCallback(progress) → voidengine.js:445
progress number

The part of the loads done, 0 to 1

ObjectCallbackFunction(object) → voidengine.js:1152
object EngineObject
PluginCallback() → voidengine.js:356