### Pre-Render Setup Source: https://killedbyapixel.github.io/LittleJS/docs/src_engineWebGL.js.html Performs essential setup before rendering each frame, including clearing the canvas, building the transform matrix, and setting up shaders and textures. It also forces instanced mode. ```javascript function glPreRender(clear=true) { if (!glEnable || !glContext) return; ASSERT(!glBatchCount, 'glPreRender called with unflushed batch.'); if (!glRenderTarget) { // set to same size as main canvas glCanvas.width = mainCanvasSize.x; glCanvas.height = mainCanvasSize.y; } glContext.viewport(0, 0, mainCanvasSize.x, mainCanvasSize.y); clear && glClearCanvas(); // build the transform matrix const s = vec2(2*cameraScale).divide(mainCanvasSize); if (glRenderTarget) s.y = -s.y; // invert y when using render target const rotatedCam = cameraPos.rotate(-cameraAngle); const p = vec2(-1).subtract(rotatedCam.multiply(s)); const ca = cos(cameraAngle); const sa = sin(cameraAngle); const transform = [ s.x * ca, s.y * sa, 0, 0, -s.x * sa, s.y * ca, 0, 0, 1, 1, 1, 0, p.x, p.y, 0, 1]; // set the same transform matrix for both shaders const initUniform = (program, uniform, value)=> { glContext.useProgram(program); const location = glContext.getUniformLocation(program, uniform); glContext.uniformMatrix4fv(location, false, value); } initUniform(glPolyShader, 'm', transform); initUniform(glShader, 'm', transform); // set the active texture glContext.activeTexture(glContext.TEXTURE0); if (textureInfos[0]) { glActiveTexture = textureInfos[0].glTexture; glContext.bindTexture(glContext.TEXTURE_2D, glActiveTexture); } // rebind the array buffer glContext.bindBuffer(glContext.ARRAY_BUFFER, glArrayBuffer); // start with additive blending off glAdditive = glBatchAdditive = false; // force it to set instanced mode glSetInstancedMode(true); } ``` -------------------------------- ### Start Sound Instance with Offset Source: https://killedbyapixel.github.io/LittleJS/docs/Audio.SoundInstance.html Use this to start playing a sound instance from a specific time offset. If no offset is provided, playback begins from the start. ```javascript start(offsetopt) ``` -------------------------------- ### Initialize and Start LittleJS Engine Source: https://killedbyapixel.github.io/LittleJS/docs/src_engine.js.html Sets up the main canvas, initializes input and audio, loads assets, and starts the game engine. Handles splash screen display and waits for all assets to load before calling gameInit and engineUpdate. ```javascript function initEngine(rootElement, showSplashScreen, canvasPixelated, imageSources, fontImageInit, gameInit) { // setup root element const styleRoot = 'position:absolute;width:100%;height:100%;overflow:hidden;background-color:black;' rootElement.style.cssText = styleRoot; // setup main canvas mainCanvas = rootElement.appendChild(document.createElement('canvas')); drawContext = mainContext = mainCanvas.getContext('2d'); // init stuff and start engine inputInit(); audioInit(); debugInit(); // setup canvases // transform way is still more reliable than flexbox or grid const styleCanvas = 'position:absolute;'+ // allow canvases to overlap 'top:50%;left:50%;transform:translate(-50%,-50%)'; // center on screen mainCanvas.style.cssText = styleCanvas; if (glCanvas) glCanvas.style.cssText = styleCanvas; setCanvasPixelated(canvasPixelated); updateCanvas(); glPreRender(); // create offscreen canvases for image processing workCanvas = new OffscreenCanvas(64, 64); workContext = workCanvas.getContext('2d'); workReadCanvas = new OffscreenCanvas(64, 64); workReadContext = workReadCanvas.getContext('2d', { willReadFrequently: true }); // create promises for loading images const promises = imageSources.map((src, i)=> loadTexture(i, src)); // no images to load if (!imageSources.length) promises.push(loadTexture(0)); // load engine font image promises.push(fontImageInit()); if (showSplashScreen) { // draw splash screen promises.push(new Promise(resolve => { let t = 0; updateSplash(); function updateSplash() { inputClear(); drawEngineLogo(t+=.01); t>1 ? resolve() : setTimeout(updateSplash, 16); } })); } // wait for all the promises to finish await Promise.all(promises); return startEngine(); async function startEngine() { // wait for gameInit to load await gameInit(); engineUpdate(); } } ``` -------------------------------- ### Start Sound Instance - JavaScript Source: https://killedbyapixel.github.io/LittleJS/docs/src_engineAudio.js.html Starts or restarts a sound instance from a specified offset. Ensures any existing playback is stopped before starting anew. ```javascript start(offset=0) { ASSERT(offset >= 0, 'Sound start offset must be positive or zero'); if (this.isPlaying()) this.stop(); this.gainNode = audioContext.createGain(); this.source = playSamples(this.sound.sampleChannels, this.volume, this.rate, this.pan, this.loop, this.sound.sampleRate, this.gainNode, offset, this.onendedCallback); if (this.source) { this.startTime = audioContext.currentTime - offset; this.pausedTime = undefined; } else { this.startTime = undefined; this.pausedTime = 0; } } ``` -------------------------------- ### ParticleEmitter Constructor Example Source: https://killedbyapixel.github.io/LittleJS/docs/src_engineParticles.js.html This example demonstrates how to create a particle emitter with various settings for position, emission properties, colors, particle behavior, and rendering. ```javascript let pos = vec2(2,3); let particleEmitter = new ParticleEmitter ( pos, 0, 1, 0, 500, PI, // pos, angle, emitSize, emitTime, emitRate, emitCone tile(0, 16), rgb(1,1,1,1), rgb(0,0,0,1), // colorStartA, colorStartB rgb(1,1,1,0), rgb(0,0,0,0), // colorEndA, colorEndB 1, .2, .2, .1, .05, // particleTime, sizeStart, sizeEnd, particleSpeed, particleAngleSpeed .99, 1, 1, PI, .05, // damping, angleDamping, gravityScale, particleCone, fadeRate, .5, 1 // randomness, collide, additive, randomColorLinear, renderOrder ); ``` -------------------------------- ### debugVideoCaptureStart Source: https://killedbyapixel.github.io/LittleJS/docs/Debug.html Starts the video capture process. ```APIDOC ## debugVideoCaptureStart() ### Description Start capturing video. ``` -------------------------------- ### raycastAll(start, end) Source: https://killedbyapixel.github.io/LittleJS/docs/Box2D.Box2dPlugin.html Performs a raycast and returns a list of all results. ```APIDOC ## raycastAll(start, end) ### Description Raycast and return a list of all the results. ### Parameters #### Path Parameters - **start** (Vector2) - Required - **end** (Vector2) - Required ``` -------------------------------- ### Create and Control a Sound Instance Source: https://killedbyapixel.github.io/LittleJS/docs/Audio.SoundInstance.html Use this to play a sound and gain control over its individual instance. You can set volume, pause, resume, and stop the sound after it has started. ```javascript const jumpSound = new Sound([.5,.5,220]); const instance = jumpSound.play(); // Control the individual instance instance.setVolume(.5); instance.pause(); instance.resume(); instance.stop(); ``` -------------------------------- ### Engine Initialization and Callbacks Source: https://killedbyapixel.github.io/LittleJS/docs/src_engine.js.html The `engineInit` function is the entry point for starting the LittleJS engine. It accepts callback functions for game initialization, updates, and rendering. ```APIDOC ## engineInit(gameInit, gameUpdate, gameRender, gamePhysics, gameCollide) ### Description Startup LittleJS engine with your callback functions. ### Parameters #### Path Parameters - **gameInit** (GameInitCallback) - Called once after the engine starts up, can be async for loading. - **gameUpdate** (GameCallback) - Called every frame for game logic updates. - **gameRender** (GameCallback) - Called every frame for rendering game visuals. - **gamePhysics** (GameCallback) - Called every frame for physics updates. - **gameCollide** (GameCallback) - Called every frame for collision detection and response. ``` -------------------------------- ### raycast(start, end) Source: https://killedbyapixel.github.io/LittleJS/docs/Box2D.Box2dPlugin.html Performs a raycast and returns the first result. ```APIDOC ## raycast(start, end) ### Description Raycast and return the first result. ### Parameters #### Path Parameters - **start** (Vector2) - Required - **end** (Vector2) - Required ``` -------------------------------- ### Engine Initialization Source: https://killedbyapixel.github.io/LittleJS/docs/src_engine.js.html The `engineInit` function is the entry point for starting the LittleJS engine. It accepts game-specific initialization and callback functions. ```javascript /** Startup LittleJS engine with your callback functions * @param {GameInitCallback} gameInit - Called once after the engine starts up, can be async for loading */ function engineInit(gameInit) {} ``` -------------------------------- ### raycastAll Source: https://killedbyapixel.github.io/LittleJS/docs/plugins_box2d.js.html Performs a raycast from a start point to an end point and returns a list of all fixtures hit by the ray. ```APIDOC ## raycastAll ### Description Performs a raycast from a start point to an end point and returns an array of all fixtures that the ray intersects. Each result includes the fixture, the point of intersection, the normal vector, and the fraction of the ray's length to the hit point. ### Method `raycastAll(start, end)` ### Parameters * **start** (Vector2) - The starting point of the ray. * **end** (Vector2) - The ending point of the ray. ### Response * **Array** - An array of results, where each result contains `fixture`, `point`, `normal`, and `fraction`. ``` -------------------------------- ### Camera Settings for LittleJS Source: https://killedbyapixel.github.io/LittleJS/docs/src_engineSettings.js.html Configure camera position, rotation, and scale for world-space rendering. Defaults are provided for initial setup. ```javascript let cameraPos = vec2(); let cameraAngle = 0; let cameraScale = 32; ``` -------------------------------- ### Get current video time Source: https://killedbyapixel.github.io/LittleJS/docs/plugins_uiSystem.js.html Retrieves the current playback time of the video in seconds. Returns 0 if the video has not started or has no current time. ```javascript getCurrentTime() { return this.video.currentTime || 0; } ``` -------------------------------- ### Initialize LittleJS Engine Source: https://killedbyapixel.github.io/LittleJS/docs/Engine.html Startup LittleJS engine with your callback functions. Use gameInit for one-time setup, gameUpdate for game logic, gameUpdatePost for UI updates, gameRender for background drawing, and gameRenderPost for UI overlays. You can also preload images and specify a root DOM element. ```javascript engineInit( ()=> { LOG('Game initialized!'); }, // gameInit ()=> { updateGameLogic(); }, // gameUpdate ()=> { updateUI(); }, // gameUpdatePost ()=> { drawBackground(); }, // gameRender ()=> { drawHUD(); }, // gameRenderPost ['tiles.png', 'tilesLevel.png'] // images to load ); ``` -------------------------------- ### Create and Play Sound - LittleJS Source: https://killedbyapixel.github.io/LittleJS/docs/Audio.Sound.html Demonstrates how to create a Sound object by loading an audio file or using ZzFX parameters, and then play the sound. Ensure user interaction before playing sounds. ```javascript const sound_example = new Sound('sound.mp3'); ``` ```javascript const sound_example = new Sound([.5,.5]); ``` ```javascript sound_example.play(); ``` -------------------------------- ### Get Duration Source: https://killedbyapixel.github.io/LittleJS/docs/src_engineAudio.js.html Gets the duration of the loaded sound in seconds. ```APIDOC ## getDuration ### Description Gets how long this sound is in seconds. ### Method `getDuration()` ### Returns - **number** - How long the sound is in seconds (undefined if loading). ``` -------------------------------- ### Start Redraw Process Source: https://killedbyapixel.github.io/LittleJS/docs/src_engineTileLayer.js.html Prepares the drawing context for a redraw operation. Saves current render settings and sets the layer's context and camera properties. ```javascript redrawStart(clear=false) { if (!this.context) return; ASSERT(drawContext !== this.context); // save current render settings /** @type {[CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D, Vector2, Vector2, number, Color]} */ this.savedRenderSettings = [drawContext, mainCanvasSize, cameraPos, cameraScale, canvasClearColor]; // set the draw canvas and context to this layer // use camera settings to match this layer's canvas drawContext = this.context; const tileSize = this.tileInfo?.size ?? vec2(1); mainCanvasSize = this.size.multiply(tileSize); canvasClearColor = CLEAR_BLACK; cameraPos = this.size.multiply(tileSize).scale(.5); cameraScale = 1; } ``` -------------------------------- ### Get Current Playback Time Source: https://killedbyapixel.github.io/LittleJS/docs/Audio.SoundInstance.html Use this to get the current playback time of the sound instance in seconds. ```javascript getCurrentTime() → {number} ``` -------------------------------- ### UISystemPlugin Initialization Source: https://killedbyapixel.github.io/LittleJS/docs/UISystem.html Instantiate the UISystemPlugin to set up the UI system for your game. This plugin supports gamepad and keyboard navigation, nested menus, and various UI elements. ```APIDOC ## Initialize UI System ### Description Call `new UISystemPlugin()` to set up the UI system. This enables features like gamepad and keyboard navigation, nested menus, and various UI elements. ### Method ```javascript new UISystemPlugin() ``` ### Usage ```javascript // Assuming UISystemPlugin is imported or available in scope const uiSystem = new UISystemPlugin(); ``` ``` -------------------------------- ### Initialize UI System Plugin Source: https://killedbyapixel.github.io/LittleJS/docs/plugins_uiSystem.js.html Initializes the UI system with a rendering context and sets up event listeners for keyboard input. The plugin manages active and hover objects, as well as confirmation dialogs and key input targets. ```javascript this.uiContext = context; this.activeObject = undefined; this.hoverObject = undefined; this.lastHoverObject = undefined; this.confirmDialog = undefined; this.keyInputObject = undefined; engineAddPlugin(uiUpdate, uiRender); // key down handler function onKeyDown(e) { uiSystem.keyInputObject?.onKeyDown(e); } document.addEventListener('keydown', onKeyDown); ``` -------------------------------- ### setupDragAndDrop Source: https://killedbyapixel.github.io/LittleJS/docs/plugins_uiSystem.js.html Sets up event listeners for drag and drop operations on the window. It accepts callbacks for when a file is dropped, enters the window, leaves the window, or is dragged over the window. ```APIDOC ## setupDragAndDrop ### Description Sets up event listeners for drag and drop operations. ### Parameters * **onDrop** (DragAndDropCallback) - Optional - Callback function when a file is dropped. * **onDragEnter** (DragAndDropCallback) - Optional - Callback function when a file is dragged onto the window. * **onDragLeave** (DragAndDropCallback) - Optional - Callback function when a file is dragged off the window. * **onDragOver** (DragAndDropCallback) - Optional - Callback function continuously when dragging over the window. ``` -------------------------------- ### Revolute Joint - Get Joint Speed - Box2D.js Source: https://killedbyapixel.github.io/LittleJS/docs/plugins_box2d.js.html Gets the current angular speed of the revolute joint in radians per second. This is useful for dynamic simulations and understanding how fast the joint is rotating. ```javascript getJointSpeed() { return this.box2dJoint.GetJointSpeed(); } ``` -------------------------------- ### Create Color Instances Source: https://killedbyapixel.github.io/LittleJS/docs/Engine.Color.html Demonstrates creating Color objects with default values, specific RGB components, or using helper functions like rgb() and hsl(). ```javascript let a = new Color; let b = new Color(1, 0, 0); let c = new Color(0, 0, 0, 0); let d = rgb(0, 0, 1); let e = hsl(.3, 1, .5); ``` -------------------------------- ### Revolute Joint - Get Reference Angle - Box2D.js Source: https://killedbyapixel.github.io/LittleJS/docs/plugins_box2d.js.html Gets the reference angle for a revolute joint, which is the difference between objectB's angle and objectA's angle in the reference state. This helps in understanding the joint's initial orientation. ```javascript getReferenceAngle() { return this.box2dJoint.GetReferenceAngle(); } ``` -------------------------------- ### glRegisterTextureInfo Source: https://killedbyapixel.github.io/LittleJS/docs/WebGL.html Tells WebGL to create or update the glTexture and start tracking it. ```APIDOC ## glRegisterTextureInfo(textureInfo) ### Description Tells WebGL to create or update the glTexture and start tracking it. ### Parameters #### Path Parameters - **textureInfo** (TextureInfo) - Required ``` -------------------------------- ### Create UISystemPlugin Instance Source: https://killedbyapixel.github.io/LittleJS/docs/UISystem.UISystemPlugin.html Instantiate the global UI system object. This is typically done without any arguments. ```javascript new UISystemPlugin; ``` -------------------------------- ### getNavigationDirection Source: https://killedbyapixel.github.io/LittleJS/docs/UISystem.UISystemPlugin.html Gets the current navigation direction input from a gamepad or keyboard. ```APIDOC ## getNavigationDirection() → {number} ### Description Get navigation direction from gamepad or keyboard. ### Returns - `number` - The navigation direction. ``` -------------------------------- ### Instanced Rendering VAO Setup (JavaScript) Source: https://killedbyapixel.github.io/LittleJS/docs/src_engineWebGL.js.html Sets up a Vertex Array Object (VAO) for instanced rendering. It configures vertex attributes for geometry, position, texture coordinates, color, additive color, and rotation, enabling instanced drawing. ```javascript glInstancedVAO = glContext.createVertexArray(); glContext.bindVertexArray(glInstancedVAO); offset = 0, shader = glShader, stride = gl_INSTANCE_BYTE_STRIDE; glContext.bindBuffer(glContext.ARRAY_BUFFER, glGeometryBuffer); initVertexAttrib('g', glContext.FLOAT, 0, 2); glContext.bindBuffer(glContext.ARRAY_BUFFER, glArrayBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, gl_ARRAY_BUFFER_SIZE, glContext.DYNAMIC_DRAW); initVertexAttrib('p', glContext.FLOAT, 4, 4, 1); initVertexAttrib('u', glContext.FLOAT, 4, 4, 1); initVertexAttrib('c', glContext.UNSIGNED_BYTE, 1, 4, 1); initVertexAttrib('a', glContext.UNSIGNED_BYTE, 1, 4, 1); initVertexAttrib('r', glContext.FLOAT, 4, 1, 1); ``` -------------------------------- ### Spring Properties Source: https://killedbyapixel.github.io/LittleJS/docs/Box2D.Box2dWheelJoint.html Methods for setting and getting spring properties for the joint. ```APIDOC ## setSpringFrequencyHz(hz) ### Description Sets the spring frequency in Hertz. ### Parameters - **hz** (number) - Required - The desired spring frequency in Hertz. ## getSpringFrequencyHz() → {number} ### Description Gets the spring frequency in Hertz. ### Returns - **number**: The spring frequency in Hertz. ## setSpringDampingRatio(ratio) ### Description Sets the spring damping ratio. ### Parameters - **ratio** (number) - Required - The desired spring damping ratio. ## getSpringDampingRatio() → {number} ### Description Gets the spring damping ratio. ### Returns - **number**: The spring damping ratio. ``` -------------------------------- ### Physics Get Functions Source: https://killedbyapixel.github.io/LittleJS/docs/plugins_box2d.js.html Methods for retrieving various physics properties of the body. ```APIDOC ## getCenterOfMass() ### Description Gets the center of mass of the physics body. ### Method `getCenterOfMass` ### Parameters None ### Return - `Vector2`: The center of mass. ``` ```APIDOC ## getLinearVelocity() ### Description Gets the linear velocity of the physics body. ### Method `getLinearVelocity` ### Parameters None ### Return - `Vector2`: The linear velocity. ``` ```APIDOC ## getAngularVelocity() ### Description Gets the angular velocity of the physics body. ### Method `getAngularVelocity` ### Parameters None ### Return - `number`: The angular velocity. ``` ```APIDOC ## getMass() ### Description Gets the mass of the physics body. ### Method `getMass` ### Parameters None ### Return - `number`: The mass. ``` ```APIDOC ## getInertia() ### Description Gets the rotational inertia of the physics body. ### Method `getInertia` ### Parameters None ### Return - `number`: The rotational inertia. ``` ```APIDOC ## getIsAwake() ### Description Checks if the physics body is currently awake. ### Method `getIsAwake` ### Parameters None ### Return - `boolean`: True if the body is awake, false otherwise. ``` ```APIDOC ## getBodyType() ### Description Gets the type of the physics body (e.g., static, dynamic, kinematic). ### Method `getBodyType` ### Parameters None ### Return - `number`: The body type. ``` ```APIDOC ## getSpeed() ### Description Calculates and returns the speed of the physics body based on its linear velocity. ### Method `getSpeed` ### Parameters None ### Return - `number`: The speed of the body. ``` -------------------------------- ### SoundInstance Methods Source: https://killedbyapixel.github.io/LittleJS/docs/Audio.SoundInstance.html Methods for controlling a sound instance. ```APIDOC ## getCurrentTime() → {number} ### Description Get the current playback time in seconds. ### Returns - Current playback time (number). ``` ```APIDOC ## getDuration() → {number} ### Description Get the total duration of this sound. ### Returns - Total duration in seconds (number). ``` ```APIDOC ## getSource() → {AudioBufferSourceNode} ### Description Get source of this sound instance. ### Returns - Source node (AudioBufferSourceNode). ``` ```APIDOC ## isPaused() → {boolean} ### Description Check if this instance is paused or stopped (not currently playing). ### Returns - True if not playing (boolean). ``` ```APIDOC ## isPlaying() → {boolean} ### Description Check if this instance is currently playing. ### Returns - True if playing (boolean). ``` ```APIDOC ## pause() ### Description Pause this sound instance. ``` ```APIDOC ## resume() ### Description Resume this sound instance. ``` ```APIDOC ## setVolume(volume) ### Description Set the volume of this sound instance. ### Parameters #### Parameters - **volume** (number) - The desired volume. ``` ```APIDOC ## start(offset?) ### Description Start playing the sound instance from the offset time. ### Parameters #### Parameters - **offset** (number) - Optional - Offset in seconds to start playback from. Defaults to 0. ``` -------------------------------- ### Methods Source: https://killedbyapixel.github.io/LittleJS/docs/Box2D.Box2dTargetJoint.html Provides methods to get and set properties of the Box2D Target Joint. ```APIDOC ## Methods ### getFrequency() #### Description Gets the joint frequency in Hertz. #### Returns - **number**: The current frequency of the joint. ``` ```APIDOC ## Methods ### getMaxForce() #### Description Gets the maximum force the joint can apply in Newtons. #### Returns - **number**: The maximum force allowed. ``` ```APIDOC ## Methods ### getTarget() #### Description Gets the target point in world coordinates that the joint is trying to reach. #### Returns - **Vector2**: The current target point. ``` ```APIDOC ## Methods ### setFrequency(hz) #### Description Sets the joint frequency in Hertz. This controls how stiff the constraint is. #### Parameters - **hz** (number) - The desired frequency in Hertz. ``` ```APIDOC ## Methods ### setMaxForce(force) #### Description Sets the maximum force in Newtons that the joint can apply. This prevents the constraint from becoming too rigid. #### Parameters - **force** (number) - The maximum force allowed in Newtons. ``` ```APIDOC ## Methods ### setTarget(pos) #### Description Sets the target point in world coordinates for the joint to track. #### Parameters - **pos** (Vector2) - The new target point in world coordinates. ``` -------------------------------- ### Initialize WebGL and HTML Styles in JavaScript Source: https://killedbyapixel.github.io/LittleJS/docs/src_engine.js.html Sets up the WebGL context and applies essential CSS styles to the root element for game display. This includes setting margins, overflow, background color, and preventing text selection. ```javascript // skip setup if headless if (headlessMode) return startEngine(); // setup webgl glInit(rootElement); // setup html const styleRoot = 'margin:0;' + // fill the window 'overflow:hidden;' + // no scroll bars 'background:#000;' + // set background color 'user-select:none;' + // prevent hold to select '' ``` -------------------------------- ### Sound Instance Methods Source: https://killedbyapixel.github.io/LittleJS/docs/src_engineAudio.js.html Methods for controlling individual sound instances, such as setting volume, stopping, pausing, and resuming playback. ```APIDOC ## setVolume(volume) ### Description Set the volume of this sound instance. ### Parameters #### Path Parameters - **volume** (number) - The desired volume level. ### Method Instance Method ``` ```APIDOC ## stop(fadeTime) ### Description Stop this sound instance and reset position to the start. Optionally fade out over a specified time. ### Parameters #### Path Parameters - **fadeTime** (number) - Optional. The time in seconds to fade out the sound. Defaults to 0. ### Method Instance Method ``` ```APIDOC ## pause() ### Description Pause this sound instance. The current playback time is saved. ### Method Instance Method ``` ```APIDOC ## resume() ### Description Resume this sound instance from its paused position. ### Method Instance Method ``` ```APIDOC ## isPlaying() ### Description Check if this instance is currently playing. ### Returns - **boolean** - True if playing, false otherwise. ### Method Instance Method ``` ```APIDOC ## isPaused() ### Description Check if this instance is paused or stopped (not currently playing). ### Returns - **boolean** - True if not playing, false otherwise. ### Method Instance Method ``` ```APIDOC ## getCurrentTime() ### Description Get the current playback time in seconds. ### Returns - **number** - Current playback time in seconds. ### Method Instance Method ``` ```APIDOC ## getDuration() ### Description Get the total duration of this sound in seconds. ### Returns - **number** - Total duration in seconds. ### Method Instance Method ``` ```APIDOC ## getSource() ### Description Get the audio source node of this sound instance. ### Returns - **AudioBufferSourceNode** - The audio source node. ### Method Instance Method ``` -------------------------------- ### Box2dWeldJoint Methods Source: https://killedbyapixel.github.io/LittleJS/docs/Box2D.Box2dWeldJoint.html Provides methods to get and set properties of the weld joint. ```APIDOC ## getFrequency() ### Description Gets the frequency in Hertz of the weld joint. ### Returns - **number**: The frequency in Hertz. ``` ```APIDOC ## getLocalAnchorA() ### Description Gets the local anchor point relative to objectA's origin. ### Returns - **Vector2**: The local anchor point on objectA. ``` ```APIDOC ## getLocalAnchorB() ### Description Gets the local anchor point relative to objectB's origin. ### Returns - **Vector2**: The local anchor point on objectB. ``` ```APIDOC ## getReferenceAngle() ### Description Gets the reference angle of the weld joint. ### Returns - **number**: The reference angle. ``` ```APIDOC ## getSpringDampingRatio() ### Description Gets the damping ratio of the weld joint. ### Returns - **number**: The damping ratio. ``` ```APIDOC ## setFrequency(hz) ### Description Sets the frequency in Hertz for the weld joint. ### Parameters #### Parameters - **hz** (number) - The frequency in Hertz. ``` ```APIDOC ## setSpringDampingRatio(ratio) ### Description Sets the damping ratio for the weld joint. ### Parameters #### Parameters - **ratio** (number) - The damping ratio. ``` -------------------------------- ### setGLEnable Source: https://killedbyapixel.github.io/LittleJS/docs/src_engineSettings.js.html Enables or disables WebGL rendering. If WebGL was disabled on start, it cannot be enabled later. ```APIDOC ## setGLEnable(enable) ### Description Enables or disables WebGL rendering. If WebGL was disabled on start, it cannot be enabled later. ### Parameters #### Path Parameters - **enable** (boolean) - Required - Whether to enable WebGL. ``` -------------------------------- ### Initialize Input System - LittleJS Source: https://killedbyapixel.github.io/LittleJS/docs/src_engineInput.js.html Sets up event listeners for keyboard, mouse, and touch input. Initializes the input data structures and enables touch input if applicable and enabled. ```javascript function inputInit() { if (headlessMode) return; // add event listeners document.addEventListener('keydown', onKeyDown); document.addEventListener('keyup', onKeyUp); document.addEventListener('mousedown', onMouseDown); document.addEventListener('mouseup', onMouseUp); document.addEventListener('mousemove', onMouseMove); document.addEventListener('mouseleave', onMouseLeave); document.addEventListener('wheel', onMouseWheel, { passive: false }); document.addEventListener('contextmenu', onContextMenu); document.addEventListener('blur', onBlur); // init touch input if (isTouchDevice && touchInputEnable) touchInputInit(); function onKeyDown(e) { if (!e.repeat) { isUsingGamepad = false; inputData[0][e.code] = 3; if (inputWASDEmulateDirection) inputData[0][remapKey(e.code)] = 3; } // try to prevent default browser handling of input if (!inputPreventDefault || !e.cancelable || !document.hasFocus()) return; // don't break browser shortcuts if (e.ctrlKey || e.metaKey || e.altKey) return; // don't interfere with user typing into UI fields if (isTextInput(e.target) || isTextInput(document.activeElement)) return; // fix browser setting "Search for text when you start typing" const printable = typeof e.key === 'string' && e.key.length === 1; // prevent arrow key and other default keys from messing with stuff const preventDefaultKeys = [ 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', // scrolling 'Space', // page down scroll 'Tab', // focus navigation 'Backspace', // browser back ]; if (preventDefaultKeys.includes(e.code) || printable) e.preventDefault(); function isTextInput(element) { const tag = element?.tagName; const editable = element?.isContentEditable; return editable || ['INPUT','TEXTAREA','SELECT'].includes(tag); } } function onKeyUp(e) { inputData[0][e.code] = (inputData[0][e.code]&2) | 4; if (inputWASDEmulateDirection) inputData[0][remapKey(e.code)] = 4; } function remapKey(k) { // handle remapping wasd keys to directions return inputWASDEmulateDirection ? k === 'KeyW' ? 'ArrowUp' : k === 'KeyS' ? 'ArrowDown' : k === 'KeyA' ? 'ArrowLeft' : k === 'KeyD' ? 'ArrowRight' : k : k; } function onMouseDown(e) { if (isTouchDevice && touchInputEnable) return; // fix stalled audio requiring user interaction if (soundEnable && !headlessMode && audioContext && !audioIsRunning()) audioContext.resume(); isUsingGamepad = false; inputData[0][e.button] = 3; const mousePosScreenLast = mousePosScreen; mousePosScreen = mouseEventToScreen(vec2(e.x,e.y)); mouseDeltaScreen = mouseDeltaScreen.add(mousePosScreen.subtract(mousePosScreenLast)); if (inputPreventDefault && e.cancelable && document.hasFocus()) e.preventDefault(); } function onMouseUp(e) { if (isTouchDevice && touchInputEnable) return; inputData[0][e.button] = (inputData[0][e.button]&2) | 4; } function onMouseMove(e) { mouseInWindow = true; ``` -------------------------------- ### Start Video Capture Source: https://killedbyapixel.github.io/LittleJS/docs/src_engineDebug.js.html Initiates video recording of the game canvas, optionally including audio. It sets up a MediaRecorder and connects audio streams if enabled. Handles browser compatibility issues. ```javascript const mediaRecorder = new MediaRecorder(stream, {mimeType:'video/webm;codecs=vp8'}); mediaRecorder.ondataavailable = (e)=> chunks.push(e.data); mediaRecorder.onstop = ()=> { const blob = new Blob(chunks, {type: 'video/webm'}); const url = URL.createObjectURL(blob); saveDataURL(url, 'capture.webm', 1e3); }; let audioStreamDestination, silentAudioSource; if (soundEnable) { silentAudioSource = new ConstantSourceNode(audioContext, { offset: 0 }); silentAudioSource.connect(audioMasterGain); silentAudioSource.start(); audioStreamDestination = audioContext.createMediaStreamDestination(); audioMasterGain.connect(audioStreamDestination); for (const track of audioStreamDestination.stream.getAudioTracks()) stream.addTrack(track); } try { mediaRecorder.start(); } catch(e) { LOG('Video capture not supported in this browser!'); silentAudioSource?.stop(); return; } LOG('Video capture started.'); debugVideoCapture = { mediaRecorder, captureTimer, videoTrack, silentAudioSource, audioStreamDestination }; ``` -------------------------------- ### Transformations Source: https://killedbyapixel.github.io/LittleJS/docs/src_engineObject.js.html Methods for converting vectors between local and world spaces, and for getting directional vectors. ```APIDOC ## localToWorldVector(vec) ### Description Converts a vector from local space to world space. ### Method `localToWorldVector` ### Parameters #### Path Parameters - **vec** (Vector2) - The vector in local space to convert. ### Response #### Success Response (Vector2) Returns the vector in world space. ``` ```APIDOC ## worldToLocalVector(vec) ### Description Convert from world space to local space for a vector (rotation only). ### Method `worldToLocalVector` ### Parameters #### Path Parameters - **vec** (Vector2) - World space vector. ### Response #### Success Response (Vector2) Returns the vector in local space. ``` ```APIDOC ## getUp(scale) ### Description Get this object's up vector. ### Method `getUp` ### Parameters #### Path Parameters - **scale** (number) - Optional. The desired length of the vector. Defaults to 1. ### Response #### Success Response (Vector2) Returns the up vector. ``` ```APIDOC ## getRight(scale) ### Description Get this object's right vector. ### Method `getRight` ### Parameters #### Path Parameters - **scale** (number) - Optional. The desired length of the vector. Defaults to 1. ### Response #### Success Response (Vector2) Returns the right vector. ``` -------------------------------- ### raycast Source: https://killedbyapixel.github.io/LittleJS/docs/plugins_box2d.js.html Performs a raycast and returns the first fixture hit by the ray, closest to the start point. ```APIDOC ## raycast ### Description Performs a raycast from a start point to an end point and returns the first fixture hit by the ray, which is the one with the smallest fraction (closest to the start point). If no fixtures are hit, it returns `undefined`. ### Method `raycast(start, end)` ### Parameters * **start** (Vector2) - The starting point of the ray. * **end** (Vector2) - The ending point of the ray. ### Response * **Box2dRaycastResult | undefined** - The closest hit result, or `undefined` if no fixture was hit. ``` -------------------------------- ### setupDragAndDrop Source: https://killedbyapixel.github.io/LittleJS/docs/UISystem.UISystemPlugin.html Sets up event handlers for drag and drop functionality, automatically preventing default behaviors. ```APIDOC ## setupDragAndDrop(onDropopt, onDragEnteropt, onDragLeaveopt, onDragOveropt) ### Description Setup drag and drop event handlers. Automatically prevents defaults and calls the given functions. ### Parameters - `onDrop` (DragAndDropCallback) - Optional - Callback function executed when a file is dropped. - `onDragEnter` (DragAndDropCallback) - Optional - Callback function executed when a file is dragged onto the window. - `onDragLeave` (DragAndDropCallback) - Optional - Callback function executed when a file is dragged off the window. - `onDragOver` (DragAndDropCallback) - Optional - Callback function executed continuously while a file is dragged over the window. ``` -------------------------------- ### Create and Play ZzFXM Music Source: https://killedbyapixel.github.io/LittleJS/docs/plugins_zzfxm.js.html Instantiate a `Music` object with ZzFXM parameters and play it. The `Music` object caches the generated samples for later use. ```javascript const music_example = new Music( [ [,0,400] // simple note ], [ [ 0, -1, // instrument 0, left speaker 1, 0, 9, 1 // channel notes ], [ 0, 1, // instrument 0, right speaker 0, 12, 17, -1 // channel notes ] ], [0, 0, 0, 0], // sequence, play pattern 0 four times 90 // BPM ]); // play the music music_example.play(); ``` -------------------------------- ### isIntersecting(start, end, pos, size) Source: https://killedbyapixel.github.io/LittleJS/docs/Math.html Checks if a line segment intersects with an axis-aligned box. ```APIDOC ## isIntersecting(start, end, pos, size) ### Description Returns true if a line segment is intersecting an axis aligned box. ### Parameters #### Path Parameters - **start** (Vector2) - Start of raycast - **end** (Vector2) - End of raycast - **pos** (Vector2) - Center of box - **size** (Vector2) - Size of box ### Returns - True if intersecting Type: boolean ``` -------------------------------- ### engineInit Source: https://killedbyapixel.github.io/LittleJS/docs/src_engine.js.html Initializes the LittleJS engine, setting up the game loop and preloading assets. It accepts callbacks for different stages of the game loop: initialization, updates, and rendering. ```APIDOC ## engineInit ### Description Initializes the LittleJS engine, setting up the game loop and preloading assets. It accepts callbacks for different stages of the game loop: initialization, updates, and rendering. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **gameInit** (GameCallback) - Called once when the engine is initialized. Use for one-time setup. * **gameUpdate** (GameCallback) - Called every frame before objects are updated. Use for game logic. * **gameUpdatePost** (GameCallback) - Called after physics and objects are updated, even when paused. Use for UI updates. * **gameRender** (GameCallback) - Called before objects are rendered. Use for drawing backgrounds/world elements. * **gameRenderPost** (GameCallback) - Called after objects are rendered. Use for drawing UI/overlays. * **imageSources** (Array) - Optional. List of image file paths to preload (e.g., ['player.png', 'tiles.png']). Defaults to an empty array. * **rootElement** (HTMLElement) - Optional. Root DOM element to attach the canvas to. Defaults to `document.body`. ### Request Example ```javascript engineInit( () => { LOG('Game initialized!'); }, // gameInit () => { updateGameLogic(); }, // gameUpdate () => { updateUI(); }, // gameUpdatePost () => { drawBackground(); }, // gameRender () => { drawHUD(); }, // gameRenderPost ['tiles.png', 'tilesLevel.png'] // images to load ); ``` ### Response This function does not return a value directly, but initializes the engine and starts the game loop. ``` -------------------------------- ### Get Sound Source Node - LittleJS Audio Source: https://killedbyapixel.github.io/LittleJS/docs/src_engineAudio.js.html Returns the AudioBufferSourceNode associated with this sound instance. ```javascript getSource() { return this.source; } ``` -------------------------------- ### Sound Instance Constructor - JavaScript Source: https://killedbyapixel.github.io/LittleJS/docs/src_engineAudio.js.html Initializes a SoundInstance, which wraps an AudioBufferSourceNode for individual sound control. Use this to manage playback of a specific sound. ```javascript constructor(sound, volume=1, rate=1, pan=0, loop=false, paused=false) { ASSERT(sound instanceof Sound, 'SoundInstance requires a valid Sound object'); ASSERT(volume >= 0, 'Sound volume must be positive or zero'); ASSERT(rate >= 0, 'Sound rate must be positive or zero'); ASSERT(isNumber(pan), 'Sound pan must be a number'); /** @property {Sound} - The sound object */ this.sound = sound; /** @property {number} - How much to scale volume by */ this.volume = volume; /** @property {number} - The playback rate to use */ this.rate = rate; /** @property {number} - How much to apply stereo panning */ this.pan = pan; /** @property {boolean} - Should the sound loop */ this.loop = loop; /** @property {number} - Timestamp for audio context when paused */ this.pausedTime = 0; /** @property {number} - Timestamp for audio context when started */ this.startTime = undefined; /** @property {GainNode} - Gain node for the sound */ this.gainNode = undefined; /** @property {AudioBufferSourceNode} - Source node of the audio */ this.source = undefined; // setup end callback and start sound this.onendedCallback = (source)=> { if (source === this.source) this.source = undefined; }; if (!paused) this.start(); } ``` -------------------------------- ### Get Object's Speed Source: https://killedbyapixel.github.io/LittleJS/docs/src_engineObject.js.html Calculates the current speed of the object based on its velocity vector. ```javascript getSpeed() { return this.velocity.length(); } ``` -------------------------------- ### getNavigationOtherDirection Source: https://killedbyapixel.github.io/LittleJS/docs/UISystem.UISystemPlugin.html Gets the secondary navigation direction input (e.g., analog stick) from a gamepad or keyboard. ```APIDOC ## getNavigationOtherDirection() → {Vector2} ### Description Get other axis navigation direction from gamepad or keyboard. ### Returns - `Vector2` - The other axis navigation direction. ``` -------------------------------- ### UISystemPlugin Constructor Source: https://killedbyapixel.github.io/LittleJS/docs/UISystem.UISystemPlugin.html Creates the global UI system object. The context parameter is optional. ```APIDOC ## new UISystemPlugin(context?) ### Description Creates the global UI system object. ### Parameters #### Path Parameters - **context** (CanvasRenderingContext2D) - Optional - The rendering context for the canvas. ### Request Example ```javascript new UISystemPlugin; ``` ``` -------------------------------- ### maxLength Source: https://killedbyapixel.github.io/LittleJS/docs/UISystem.UITextInput.html Gets or sets the maximum length of the input text. A value of 0 means no limit. ```APIDOC ## maxLength ### Description Max length of input (0 = no limit). ### Properties - **maxLength** (number) - The maximum number of characters allowed in the input field. ``` -------------------------------- ### Constructor: new Box2dPlugin(instance) Source: https://killedbyapixel.github.io/LittleJS/docs/Box2D.Box2dPlugin.html Creates the global UI system object for the Box2D plugin. ```APIDOC ## new Box2dPlugin(instance) ### Description Create the global UI system object. ### Parameters #### Path Parameters - **instance** (Object) - Required - The source object for the instance. ``` -------------------------------- ### Get Sound Instance Source Node Source: https://killedbyapixel.github.io/LittleJS/docs/Audio.SoundInstance.html Use this to access the underlying AudioBufferSourceNode for the sound instance. ```javascript getSource() → {AudioBufferSourceNode} ``` -------------------------------- ### new UITextInput(posopt, sizeopt, textopt) Source: https://killedbyapixel.github.io/LittleJS/docs/UISystem.UITextInput.html Creates a new UITextInput object. This is the constructor for the class. ```APIDOC ## new UITextInput(posopt, sizeopt, textopt) ### Description Create a UITextInput object. ### Parameters #### Path Parameters - **pos** (Vector2) - Optional - Position of the text input. - **size** (Vector2) - Optional - Size of the text input. - **text** (string) - Optional - Initial text for the input. ``` -------------------------------- ### Box2dFrictionJoint Methods Source: https://killedbyapixel.github.io/LittleJS/docs/Box2D.Box2dFrictionJoint.html Provides methods to get and set the maximum friction force and torque for the joint. ```APIDOC ## getLocalAnchorA() ### Description Get the local anchor point relative to objectA's origin. ### Returns * `Vector2` - The local anchor point. ### Source `plugins/box2d.js`, line 1439 ``` ```APIDOC ## getLocalAnchorB() ### Description Get the local anchor point relative to objectB's origin. ### Returns * `Vector2` - The local anchor point. ### Source `plugins/box2d.js`, line 1443 ``` ```APIDOC ## getMaxForce() ### Description Get the maximum friction force. ### Returns * `number` - The maximum force. ### Source `plugins/box2d.js`, line 1451 ``` ```APIDOC ## getMaxTorque() ### Description Get the maximum friction torque. ### Returns * `number` - The maximum torque. ### Source `plugins/box2d.js`, line 1459 ``` ```APIDOC ## setMaxForce(force) ### Description Set the maximum friction force. ### Parameters * `force` (number) - The maximum force to apply. ### Source `plugins/box2d.js`, line 1447 ``` ```APIDOC ## setMaxTorque(torque) ### Description Set the maximum friction torque. ### Parameters * `torque` (number) - The maximum torque to apply. ### Source `plugins/box2d.js`, line 1455 ```