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

Color
EngineObject
RandomGenerator
Timer
Vector2

Members

(static, constant) engineName :string

Name of engine

Type:
  • string
Default Value
  • LittleJS

(static) engineObjects :Array.<EngineObject>

Array containing all engine objects

Type:
  • Array.<EngineObject>

(static) engineObjectsCollide :Array.<EngineObject>

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

Type:
  • Array.<EngineObject>

(static, constant) engineVersion :string

Version of engine

Type:
  • string
Default Value
  • 1.21.0

(static) frame :number

Current update frame, used to calculate time

Type:
  • number

(static, constant) frameRate :number

Frames per second to update

Type:
  • number
Default Value
  • 60

(static) paused :boolean

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

Type:
  • boolean
Default Value
  • false

(static) time :number

Current engine time since start in seconds

Type:
  • number

(static) timeDelta :number

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

Type:
  • number
Default Value
  • 1/60

(static) timeReal :number

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)

Type:
  • number

Methods

(static) engineAddLoad(promise) → {Promise.<any>}

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

Parameters:
NameTypeDescription
promisePromise.<any>
Returns:
  • The same promise
Type: 
Promise.<any>
Example
async function gameInit() { level = await engineAddLoad(fetchJSON('level.json')); }
 

(static) engineAddPlugin(updateopt, renderopt, glContextLostopt, glContextRestoredopt, preRenderopt)

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
Parameters:
NameTypeAttributesDescription
updatePluginCallback<optional>
renderPluginCallback<optional>
glContextLostPluginCallback<optional>
glContextRestoredPluginCallback<optional>
preRenderPluginCallback<optional>

Called after the canvas is cleared and before gameRender

(async, static) engineInit(gameInitopt, gameUpdateopt, gameUpdatePostopt, gameRenderopt, gameRenderPostopt, imageSourcesopt, rootElementopt)

Startup LittleJS engine with your callback functions

Parameters:
NameTypeAttributesDefaultDescription
gameInitGameInitCallback<optional>

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

gameUpdateGameCallback<optional>

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

gameUpdatePostGameCallback<optional>

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

gameRenderGameCallback<optional>

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

gameRenderPostGameCallback<optional>

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

imageSourcesArray.<string><optional>
[]

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

rootElementHTMLElement<optional>

Root DOM element to attach canvas to, defaults to document.body It keeps its own inline styles 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

Example
// Basic engine startup
 engineInit(
   ()=> { LOG('Game initialized!'); },  // gameInit
   ()=> { updateGameLogic(); },         // gameUpdate
   ()=> { updateUI(); },                // gameUpdatePost
   ()=> { drawBackground(); },          // gameRender
   ()=> { drawHUD(); },                 // gameRenderPost
   ['tiles.png', 'tilesLevel.png']       // images to load
 );
 

(static) engineObjectsCallback(posopt, sizeopt, callbackFunctionopt, objectsopt, testCentersopt)

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

Parameters:
NameTypeAttributesDefaultDescription
posVector2<optional>

Center of test area, or undefined for all objects

sizeVector2 | number<optional>

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

callbackFunctionObjectCallbackFunction<optional>

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

objectsArray.<EngineObject><optional>
engineObjects

List of objects to check

testCentersboolean<optional>
false

Test only each object's center, see engineObjectsCollect

(static) engineObjectsCollect(posopt, sizeopt, objectsopt, testCentersopt) → {Array.<EngineObject>}

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
Parameters:
NameTypeAttributesDefaultDescription
posVector2<optional>

Center of test area, or undefined for all objects

sizeVector2 | 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

objectsArray.<EngineObject><optional>
engineObjects

List of objects to check

testCentersboolean<optional>
false

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

Returns:
  • List of collected objects
Type: 
Array.<EngineObject>

(static) engineObjectsDestroy(immediateopt)

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
Parameters:
NameTypeAttributesDefaultDescription
immediateboolean<optional>
true

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

(static) engineObjectsRaycast(start, end, objectsopt) → {Array.<EngineObject>}

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
Parameters:
NameTypeAttributesDefaultDescription
startVector2
endVector2
objectsArray.<EngineObject><optional>
engineObjects

List of objects to check

Returns:
  • List of objects hit
Type: 
Array.<EngineObject>

(static) engineObjectsUpdate()

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

(static) engineStep(framesopt)

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

Parameters:
NameTypeAttributesDefaultDescription
framesnumber<optional>
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

Example
setHeadlessMode(true);
 setEngineManualStep(true);
 await engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost);
 engineStep(600); // advance 10 seconds of game time
 

(static) getPaused() → {boolean}

Get if game is paused

Returns:
Type: 
boolean

(static) setPaused(isPausedopt)

Set if game is paused

Parameters:
NameTypeAttributesDefaultDescription
isPausedboolean<optional>
true

Type Definitions

GameCallback()

GameInitCallback() → {void|Promise.<void>}

Returns:
Type: 
void | Promise.<void>

LoadingScreenCallback(progress)

Parameters:
NameTypeDescription
progressnumber

The part of the loads done, 0 to 1

ObjectCallbackFunction(object)

Parameters:
NameTypeDescription
objectEngineObject

PluginCallback()