### Install Dependencies and Start Dev Server Source: https://github.com/killedbyapixel/littlejs/blob/main/examples/vite-starter/README.md Install project dependencies and start the Vite development server for hot-reloading. ```bash npm install npm run dev ``` -------------------------------- ### SoundInstance Start Method Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/src_engineAudio.js.html Starts or restarts playback of the sound instance from a specified offset. If the sound is already playing, it will be stopped before starting anew. Handles setting the start time and managing the paused state. ```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; } } ``` -------------------------------- ### start(offset) Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/Audio.SoundInstance.html Starts or restarts playback of the sound instance from a specified offset. ```APIDOC ## start(offset) ### Description Start playing the sound instance from the offset time. ### Parameters #### Parameters - **offset** (number, optional) - Default: 0 - Description: Offset in seconds to start playback from. ``` -------------------------------- ### UI System Setup and Configuration Source: https://github.com/killedbyapixel/littlejs/blob/main/REFERENCE.md Initialize the UI system and configure its default styles and behavior. ```APIDOC ## Setup Initialize the UI system and configure its default styles and behavior. ```javascript // Setup const ui = new UISystemPlugin() // Creates global uiSystem uiSystem.defaultColor // Default style values used by all widgets uiSystem.defaultLineColor // (override before constructing widgets) uiSystem.defaultLineWidth uiSystem.defaultButtonColor uiSystem.defaultHoverColor uiSystem.defaultFont uiSystem.nativeHeight // If set, UI coords are normalized to this height uiSystem.destroyObjects() // Remove all UI elements uiSetDebug(enable) // Toggle uiDebug rendering of widget bounds ``` ``` -------------------------------- ### SoundInstance.start Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/src_engineAudio.js.html Starts or resumes playback of the sound instance from a specified offset. ```APIDOC ## start(offset) ### Description Starts playing the sound instance. If the sound is already playing, it will be stopped and restarted. If the sound was paused, this method resumes playback from the paused position. ### Parameters #### Parameters - **offset** (number) - Optional - Offset in seconds to start playback from. Defaults to 0. ``` -------------------------------- ### Load and Play Sound Example Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/src_engineAudio.js.html Demonstrates how to load an audio asset file and play it. Ensure the audio file is accessible. ```javascript const sound_example = new Sound('sound.mp3'); sound_example.play(); ``` -------------------------------- ### NewgroundsPlugin Setup Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/plugins_newgrounds.js.html Initialize the Newgrounds plugin by providing your application ID. This sets up the connection to the Newgrounds API. ```APIDOC ## NewgroundsPlugin Setup ### Description Call `new NewgroundsPlugin(app_id)` to set up Newgrounds integration. This function initializes the plugin and prepares it for interaction with the Newgrounds API. ### Method Constructor ### Parameters #### Path Parameters - **app_id** (string) - Required - The unique identifier for your Newgrounds application. ``` -------------------------------- ### PathFinder Example Usage Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/plugins_pathFinder.js.html Demonstrates how to initialize and use the PathFinder for finding paths on a tile layer or a custom grid. ```javascript // Tile-layer driven (most common): const pf = new PathFinder(myTileCollisionLayer); const path = pf.findPath(player.pos, mousePos); // Bare grid with custom walkability: const pf = new PathFinder(vec2(50, 50)); pf.isWalkable = (x, y) => myGrid[y*50 + x] === 0; ``` -------------------------------- ### Newgrounds Plugin Setup Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/plugins_newgrounds.js.html Initialize the Newgrounds plugin by calling the constructor with your application ID. This sets up the connection to the Newgrounds API. ```javascript new NewgroundsPlugin(app_id) ``` -------------------------------- ### Initialize Engine with Image Loading Source: https://github.com/killedbyapixel/littlejs/blob/main/FAQ.md Call engineInit with a list of image files to load on startup. The engine ensures all images are loaded before starting. ```javascript engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost, ['tiles.png']); ``` -------------------------------- ### Define Startup Sound Source: https://github.com/killedbyapixel/littlejs/blob/main/examples/breakoutTutorial/README.md Defines a sound effect to be played when the game starts. This sound can be created using the ZzFX sound designer. ```javascript const sound_start = new LJS.Sound([,0,500,,.04,.3,1,2,,,570,.02,.02,,,,.04]); ``` -------------------------------- ### Newgrounds Integration Setup Source: https://github.com/killedbyapixel/littlejs/blob/main/REFERENCE.md Initializes the Newgrounds plugin with your application ID and cipher. The `newgrounds` global is automatically set when hosted on Newgrounds. ```javascript // Newgrounds integration (only used when hosted on Newgrounds) await newgrounds // The global is set by NewgroundsPlugin new NewgroundsPlugin(app_id, cipher) // Auto-fetches medals and scoreboards ``` -------------------------------- ### TypeScript Setup with LittleJS Source: https://github.com/killedbyapixel/littlejs/blob/main/FAQ.md Integrate LittleJS with TypeScript using its provided type definitions. Install via npm for automatic type checking. ```bash npm install littlejsengine ``` ```typescript import { engineInit, drawText, vec2 } from 'littlejsengine'; function gameInit(): void {} function gameUpdate(): void {} function gameUpdatePost(): void {} function gameRender(): void {} function gameRenderPost(): void { drawText('Hello!', vec2(0,0), 4); } engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost, ['tiles.png']); ``` -------------------------------- ### UISystemPlugin Setup Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/UISystem.html Call `new UISystemPlugin()` to initialize the UI system. This plugin offers gamepad and keyboard navigation, nested menus, and various UI elements. ```APIDOC ## UISystemPlugin Setup ### Description Initialize the UI system by calling the `UISystemPlugin` constructor. This plugin enables gamepad and keyboard navigation, nested menus, and supports elements such as Text, Buttons, Checkboxes, Images, Sliders, and Video. ### Method `new UISystemPlugin()` ### Parameters None ### Request Example ```javascript new UISystemPlugin(); ``` ### Response None ``` -------------------------------- ### Tween#getValue() Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/TweenSystem.html Get the current interpolated value. The return type can be a number, Vector2, or Color, depending on the tween's start and end types. ```APIDOC ## Tween#getValue() ### Description Get the current interpolated value (the value most recently passed to the callback). Returns a number, Vector2, or Color depending on the tween's start/end types. ### Returns Type: number | Vector2 | Color ``` -------------------------------- ### Tween#getPercent() Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/TweenSystem.html Get how far this tween has progressed, from 0 (just started) to 1 (completed). This value is clamped, meaning values beyond completion still read as 1. ```APIDOC ## Tween#getPercent() ### Description Get how far this tween has progressed, from 0 (just started) to 1 (completed). Clamped — overshoot past completion still reads 1. ### Returns Type: number ``` -------------------------------- ### Create and Control a Sound Instance Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/Audio.SoundInstance.html Demonstrates how to create a sound, play it, and then control the individual instance. Use this to manage specific sound effects like jumps or UI feedback. ```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(); ``` -------------------------------- ### Initialize LightSystemPlugin Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/LightSystem.LightSystemPlugin.html Creates a new LightSystemPlugin instance. This is the simplest way to set up the global light system. ```javascript new LightSystemPlugin(); ``` -------------------------------- ### Set up Vite Project with LittleJS Source: https://github.com/killedbyapixel/littlejs/blob/main/README.md Use degit to clone the Vite starter template and set up a new game project. Includes installation and development commands. ```bash npx degit KilledByAPixel/LittleJS/examples/vite-starter my-game cd my-game npm install npm run dev ``` -------------------------------- ### Get Linear Velocity Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/plugins_box2d.js.html Gets the current linear velocity of the Box2D body as a Vector2 object. ```javascript return box2d.vec2From(this.body.GetLinearVelocity()); ``` -------------------------------- ### Install LittleJS via npm Source: https://github.com/killedbyapixel/littlejs/blob/main/README.md Use this command to install the LittleJS engine package using npm. ```bash npm install littlejsengine ``` -------------------------------- ### new Tween() Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/TweenSystem.Tween.html Creates a new tween instance. The callback fires immediately with the start value, ensuring the target snaps to the start value on the same frame the tween is created. ```APIDOC ## new Tween(callback, start, end, duration, options) ### Description Creates a new tween. The callback fires immediately with `start` so the target snaps to the start value on the same frame the tween is created. `start` and `end` may be numbers, Vector2 instances, Color instances, or any object exposing a `lerp(other, percent) => sameType` method. The callback receives the interpolated value (a number, or a fresh instance for lerp-able types). Both endpoints must be the same type. ### Parameters #### Parameters - **callback** (function) - Required - The function to call with the interpolated value. - **start** (number | Vector2 | Color) - Optional - Defaults to 0. Starting value. - **end** (number | Vector2 | Color) - Optional - Defaults to 1. Ending value. - **duration** (number) - Optional - Defaults to 1. Duration in seconds. - **options** (Object) - Optional - Configuration options for the tween. - **ease** (function) - Optional - Easing function (defaults to LINEAR). - **useRealTime** (boolean) - Optional - Defaults to false. Advance even when the game is paused. - **paused** (boolean) - Optional - Defaults to false. Start in paused state. ### Example ```javascript // Animate a fade-out over 2 seconds with an ease-out sine curve. new Tween((v) => obj.alpha = v, 1, 0, 2, { ease: Ease.OUT(Ease.SINE) }); ``` ``` -------------------------------- ### Initialize LightSystemPlugin Source: https://github.com/killedbyapixel/littlejs/blob/main/REFERENCE.md Instantiate the `LightSystemPlugin` to enable dynamic lighting. Options include specifying lightmap resolution and ambient color. ```javascript new LightSystemPlugin() // Defaults: full-canvas lightmap, BLACK ambient ``` ```javascript new LightSystemPlugin(vec2(512, 512)) // Lower-res lightmap (perf knob) ``` ```javascript new LightSystemPlugin(undefined, rgb(.1,.1,.15)) // Faint moonlight ambient ``` -------------------------------- ### getMirrorSign Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/Engine.EngineObject.html Gets the direction of the mirror. ```APIDOC ## getMirrorSign() ### Description Get the direction of the mirror. ### Returns - **number**: -1 if this.mirror is true, or 1 if not mirrored. ``` -------------------------------- ### Initialize Engine and Setup Root Element Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/src_engine.js.html Sets up the root HTML element with necessary styles for the game canvas. Initializes WebGL, input, audio, and debugging systems, then configures the main and WebGL canvases. ```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 '-webkit-user-select:none;' + // compatibility for ios 'touch-action:none;' + // prevent mobile pinch to resize '-webkit-touch-callout:none'; // compatibility for ios rootElement.style.cssText = styleRoot; 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(); ``` -------------------------------- ### Start Debug Video Capture Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/src_engineDebug.js.html Initiates video capture using the MediaRecorder API. Includes error handling for unsupported browsers and logs the start of the capture process. Stores capture-related objects for later use. ```javascript // start recording try { mediaRecorder.start(); } catch(e) { LOG('Video capture not supported in this browser!'); silentAudioSource?.stop(); audioStreamDestination && audioMasterGain.disconnect(audioStreamDestination); return; } LOG('Video capture started.'); // save debug video info debugVideoCapture = { mediaRecorder, captureTimer, videoTrack, silentAudioSource, audioStreamDestination }; } ``` -------------------------------- ### Light System Initialization and Texture Setup Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/plugins_lightSystem.js.html Initializes the light system, including creating the lightmap texture with specified dimensions and setting texture parameters for linear filtering and edge clamping. ```javascript if (headlessMode) return; if (!glEnable) { console.warn('LightSystemPlugin: WebGL not enabled!'); return; } // resolve texture size default at init time (mainCanvasSize may // not be set yet at the moment the constructor first ran) if (!lightSystem.textureSize) lightSystem.textureSize = mainCanvasSize.copy(); // allocate the lightmap texture with null data at textureSize lightSystem.texture = glContext.createTexture(); glContext.bindTexture(glContext.TEXTURE_2D, lightSystem.texture); glContext.texImage2D(glContext.TEXTURE_2D, 0, glContext.RGBA, lightSystem.textureSize.x, lightSystem.textureSize.y, 0, glContext.RGBA, glContext.UNSIGNED_BYTE, null); glContext.texParameteri(glContext.TEXTURE_2D, glContext.TEXTURE_MAG_FILTER, glContext.LINEAR); glContext.texParameteri(glContext.TEXTURE_2D, glContext.TEXTURE_MIN_FILTER, glContext.LINEAR); glContext.texParameteri(glContext.TEXTURE_2D, glContext.TEXTURE_WRAP_S, glContext.CLAMP_TO_EDGE); glContext.texParameteri(glContext.TEXTURE_2D, glContext.TEXTURE_WRAP_T, glContext.CLAMP_TO_EDGE); ``` -------------------------------- ### lastHoverObject Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/UISystem.UISystemPlugin.html Hover object at start of update. ```APIDOC ## lastHoverObject ### Description Hover object at start of update. ### Properties - **lastHoverObject** (UIObject) - Description: Hover object at start of update. ``` -------------------------------- ### getMass Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/plugins_box2d.js.html Gets the mass of the physics body. ```APIDOC ## getMass ### Description Gets the mass of the physics body. ### Method getMass() ### Returns - **number**: The mass. ``` -------------------------------- ### Create and Play ZzFXM Music Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/plugins_zzfxm.js.html Example demonstrating how to create a Music object with ZzFXM parameters and play it. This involves defining instruments, patterns, and the playback sequence. ```javascript const music_example = new Music( [ [ // instruments [,0,400] // simple note ], [ // patterns [ // pattern 1 [ // channel 0 0, -1, // instrument 0, left speaker 1, 0, 9, 1 // channel notes ], [ // channel 1 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(); ``` -------------------------------- ### Create ZzFX Sound Example Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/src_engineAudio.js.html Shows how to create a sound directly using a ZzFX array. This is useful for generating sound effects programmatically. ```javascript const sound_example = new Sound([.5,.5]); sound_example.play(); ``` -------------------------------- ### getSpringFrequencyHz Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/Box2D.Box2dWheelJoint.html Gets the spring frequency in Hertz. ```APIDOC ## getSpringFrequencyHz ### Description Gets the spring frequency in Hertz. ### Returns - **number**: The spring frequency in Hertz. ### Source * [plugins/box2d.js](plugins_box2d.js.html#line1369) ``` -------------------------------- ### Initialize Light System Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/plugins_lightSystem.js.html Initializes the light system, setting up shaders and buffers. This function is called during context restoration. ```javascript function initLightSystem() { const gl = glContext; const ls = lightSystem; ls.texture = createFramebufferTexture(1, 1); ls.lightShader = createShader(ls.lightShader || gl.createProgram(), // vertex shader "uniform mat4 m; attribute vec2 pos; varying vec2 vPos;", // fragment shader "varying vec2 vPos; uniform vec2 lightPos; uniform float radius; uniform float fadeRange; uniform vec4 color;", // vertex shader "gl_Position = m * vec4(pos, 0, 1); vPos = pos;", // fragment shader "vec2 d = vPos - lightPos; float f = 1.0 - smoothstep(radius - fadeRange, radius, sqrt(d.x*d.x + d.y*d.y)); gl_FragColor = color * f;"); ls.compositeShader = createShader(ls.compositeShader || gl.createProgram(), // vertex shader "uniform mat4 m; attribute vec2 pos; varying vec2 vPos;", // fragment shader "varying vec2 vPos; uniform sampler2D lightMap; uniform vec2 lightMapSize;", // vertex shader "gl_Position = m * vec4(pos, 0, 1); vPos = pos * .5 + .5;", // fragment shader "vec2 uv = gl_FragCoord.xy / lightMapSize; gl_FragColor = texture2D(lightMap, uv); gl_FragColor.a *= texture2D(lightMap, uv).a;"); ls.lightVAO = createVAO(ls.lightShader, [{ "pos": 2 }]); ls.compositeVAO = createVAO(ls.compositeShader, [{ "pos": 2 }]); ls.texture.bind(); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); LOG('LightSystemPlugin: Initialized'); } ``` -------------------------------- ### getSpeed() Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/Box2D.Box2dObject.html Gets the speed of the Box2D object. ```APIDOC ## getSpeed() ### Description Get the speed of this Box2D object. ### Returns - **number**: The speed of the object. ``` -------------------------------- ### getMass() Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/Box2D.Box2dObject.html Gets the mass of the Box2D object. ```APIDOC ## getMass() ### Description Gets the mass of the Box2D object. ### Returns - **number**: The mass of the object. ``` -------------------------------- ### getSpeed Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/plugins_box2d.js.html Gets the current speed of the physics body. ```APIDOC ## getSpeed ### Description Gets the current speed of the physics body. ### Method getSpeed() ### Returns - **number**: The speed of the object. ``` -------------------------------- ### Initialize WebGL Shaders and Buffers Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/src_engineWebGL.js.html Sets up the WebGL context, compiles shaders, initializes instance and geometry buffers, and configures vertex attributes for instanced and polygon rendering. This is a foundational setup for rendering. ```javascript const glInstanceData = new ArrayBuffer(gl_ARRAY_BUFFER_SIZE); glPositionData = new Float32Array(glInstanceData); glColorData = new Uint32Array(glInstanceData); glArrayBuffer = glContext.createBuffer(); glGeometryBuffer = glContext.createBuffer(); glFramebuffer = glContext.createFramebuffer(); glBatchCount = 0; // create the geometry buffer, triangle strip square const geometry = new Float32Array([0,0,1,0,0,1,1,1]); glContext.bindBuffer(glContext.ARRAY_BUFFER, glGeometryBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, geometry, glContext.STATIC_DRAW); let offset, shader, stride; const initVertexAttrib = (name, type, typeSize, size, divisor=0)=>{ const location = glContext.getAttribLocation(shader, name); const normalize = typeSize === 1; const fixedStride = typeSize && stride; glContext.enableVertexAttribArray(location); glContext.vertexAttribPointer(location, size, type, normalize, fixedStride, offset); glContext.vertexAttribDivisor(location, divisor); offset += size*typeSize; } // setup VAO for instanced rendering glInstancedVAO = glContext.createVertexArray(); glContext.bindVertexArray(glInstancedVAO); // configure instanced vertex attributes offset = 0, shader = glShader, stride = gl_INSTANCE_BYTE_STRIDE; glContext.bindBuffer(glContext.ARRAY_BUFFER, glGeometryBuffer); initVertexAttrib('g', glContext.FLOAT, 0, 2); // geometry 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); // position & size initVertexAttrib('u', glContext.FLOAT, 4, 4, 1); // texture coords initVertexAttrib('c', glContext.UNSIGNED_BYTE, 1, 4, 1); // color initVertexAttrib('a', glContext.UNSIGNED_BYTE, 1, 4, 1); // additiveColor initVertexAttrib('r', glContext.FLOAT, 4, 1, 1); // rotation // setup VAO for poly rendering glPolyVAO = glContext.createVertexArray(); glContext.bindVertexArray(glPolyVAO); // configure poly vertex attributes offset = 0, shader = glPolyShader, stride = gl_POLY_VERTEX_BYTE_STRIDE; initVertexAttrib('p', glContext.FLOAT, 4, 2); // position initVertexAttrib('c', glContext.UNSIGNED_BYTE, 1, 4); // color ``` -------------------------------- ### getLinearVelocity Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/plugins_box2d.js.html Gets the linear velocity of the physics body. ```APIDOC ## getLinearVelocity ### Description Gets the linear velocity of the physics body. ### Method getLinearVelocity() ### Returns - **Vector2**: The linear velocity. ``` -------------------------------- ### Create and Play Sound - LittleJS Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/Audio.Sound.html Demonstrates how to create a Sound object by loading an audio file or using a ZzFX array, and then play the sound. ```javascript // load an audio asset file const sound_example = new Sound('sound.mp3'); // create a zzfx sound const sound_example = new Sound([.5,.5]); // play a sound sound_example.play(); ``` -------------------------------- ### Get Mass Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/plugins_box2d.js.html Returns the mass of the Box2D body. ```javascript return this.body.GetMass(); ``` -------------------------------- ### getSpringDampingRatio Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/Box2D.Box2dWheelJoint.html Gets the spring damping ratio of the joint. ```APIDOC ## getSpringDampingRatio ### Description Gets the spring damping ratio. ### Returns - **number**: The spring damping ratio. ### Source * [plugins/box2d.js](plugins_box2d.js.html#line1377) ``` -------------------------------- ### Initialize UI System and Set Defaults Source: https://github.com/killedbyapixel/littlejs/blob/main/REFERENCE.md Instantiate the UI system and configure default styles before creating widgets. The `nativeHeight` can be set to normalize UI coordinates. ```javascript // Setup const ui = new UISystemPlugin() // Creates global uiSystem uiSystem.defaultColor // Default style values used by all widgets uiSystem.defaultLineColor // (override before constructing widgets) uiSystem.defaultLineWidth uiSystem.defaultButtonColor uiSystem.defaultHoverColor uiSystem.defaultFont uiSystem.nativeHeight // If set, UI coords are normalized to this height uiSystem.destroyObjects() // Remove all UI elements uiSetDebug(enable) // Toggle uiDebug rendering of widget bounds ``` -------------------------------- ### Initialize LittleJS and Particle System Source: https://github.com/killedbyapixel/littlejs/blob/main/examples/particles/index.html Sets up the LittleJS environment, including tile padding and input handling. Initializes the particle system and gravity. Captures the default texture for later restoration. ```javascript // import LittleJS module import * as LJS from '../../dist/littlejs.esm.js'; const {vec2} = LJS; 'use strict'; // tiles.png has 1 pixel of padding around each tile LJS.setTileDefaultPadding(1); // allow html input controls LJS.setInputPreventDefault(false); let particleEditor = 0, particleSystem, particleSystemDiv, particleSystemCode; let inputExpand; let restartTimer = new LJS.Timer(); const storagePrefix = 'particles_'; const particleSettings = []; function addSetting(name, type, min, max, step, description) { particleSettings.push({name, type:type||'number', min, max, step, description}); } addSetting('emitSize', '', 0, 1e9, .1, 'World space size of the emitter'); addSetting('emitTime', '', 0, 1e9, .1, 'How long to stay alive (0 is forever)'); addSetting('emitRate', '', 0, 1e9, 1, 'How many particles per second to spawn, does not emit if 0'); addSetting('emitConeAngle', '', 0, 1e9, .01,'Local angle to apply velocity to particles from emitter'); addSetting('tileIndex', '', -1, 1e9, 1, 'Tile to use to render object (-1 is untextured)'); addSetting('tileSize', '', 0, 1e9, 1, 'Size of texture tile in source pixels'); addSetting('tilePadding', '', 0, 1e9, 1, 'How many pixels padding around tiles'); addSetting('colorStartA', 'color',0,0,0, 'Color at start of life 1'); addSetting('colorStartA_alpha', 'alpha', 0, 1, .01, 'Alpha at start of life 1'); addSetting('colorStartB', 'color',0,0,0, 'Color at start of life 2'); addSetting('colorStartB_alpha', 'alpha', 0, 1, .01, 'Alpha at start of life 2'); addSetting('colorEndA', 'color',0,0,0, 'Color at end of life 1'); addSetting('colorEndA_alpha', 'alpha', 0, 1, .01, 'Alpha at end of life 1'); addSetting('colorEndB', 'color',0,0,0, 'Color at end of life 2'); addSetting('colorEndB_alpha', 'alpha', 0, 1, .01, 'Alpha at end of life 2'); addSetting('particleTime', '', 0, 1e9, .1, 'How long particles live'); addSetting('sizeStart', '', 0, 1e9, .01, 'How big are particles at start'); addSetting('sizeEnd', '', 0, 1e9, .01,'How big are particles at end'); addSetting('speed', '', 0, 1e9, .01,'How fast are particles when spawned'); addSetting('angleSpeed', '', 0, 1e9, .01,'How fast are particles rotating'); addSetting('damping', '', 0, 1, .01,'How much to dampen particle speed'); addSetting('angleDamping', '', 0, 1, .01,'How much to dampen particle angular speed'); addSetting('gravityScale', '', -1e9, 1e9, .1, 'How much does gravity effect particles'); addSetting('particleConeAngle','', 0, 1e9, .1, 'Cone for start particle angle'); addSetting('fadeRate', '', 0, 1, .01,'How quickly particles fade in percent of life'); addSetting('randomness', '', 0, 1, .01,'Apply extra randomness percent'); addSetting('additive', 'checkbox',0,0,0, 'Should particles use additive blend?'); addSetting('randomColorLinear','checkbox',0,0,0, 'Should color be randomized linearly?'); function makeEmitter() { if (particleSystem) particleSystem.destroy(); particleSystem = new LJS.ParticleEmitter(LJS.cameraPos); particleSystem.tileInfo = LJS.tile(); particleSystem.emitConeAngle = particleSystem.particleConeAngle = 3.14; } /////////////////////////////////////////////////////////////////////////////// // custom texture drag and drop let defaultTextureInfo; // original tiles.png texture, captured at startup let buttonDefaultTexture; // enabled only while a custom texture is active function updateTextureButton() { buttonDefaultTexture.disabled = LJS.textureInfos[0] == defaultTextureInfo; } function setCustomTexture(image) { // swap texture 0 so tile() and the generated code keep working const old = LJS.textureInfos[0]; if (old != defaultTextureInfo) old.destroyWebGLTexture(); LJS.textureInfos[0] = new LJS.TextureInfo(image); updateTextureButton(); updateParticles(1); } function restoreDefaultTexture() { delete localStorage[storagePrefix + 'textureData']; if (LJS.textureInfos[0] != defaultTextureInfo) { LJS.textureInfos[0].destroyWebGLTexture(); LJS.textureInfos[0] = defaultTextureInfo; } updateTextureButton(); } function loadCustomTexture(dataURL) { const image = new Image; image.onload = ()=> setCustomTexture(image); image.src = dataURL; } /////////////////////////////////////////////////////////////////////////////// function gameInit() { makeEmitter(); LJS.setGravity(vec2(0,-.01)); LJS.setCameraScale(64); const div = div_emitterSettings; const title = document.createElement('span') title.innerText = 'LittleJS Particle Tool'; title.style = 'font-size:20px;font-weight:bold;'; div.appendChild(title); const hint = document.createElement('div'); hint.innerText = 'Drop an image to use it as the texture'; hint.style = 'font-size:12px;color:#aaa;'; div.appendChild(hint); for (const setting of particleSettings) { // get default ``` -------------------------------- ### getMotorSpeed Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/Box2D.Box2dWheelJoint.html Gets the current motor speed of the joint. ```APIDOC ## getMotorSpeed ### Description Gets the motor speed. ### Returns - **number**: The motor speed. ### Source * [plugins/box2d.js](plugins_box2d.js.html#line1349) ``` -------------------------------- ### getLinearVelocity() Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/Box2D.Box2dObject.html Gets the linear velocity of the Box2D object. ```APIDOC ## getLinearVelocity() ### Description Gets the linear velocity of the Box2D object. ### Returns - **Vector2**: The linear velocity of the object. ``` -------------------------------- ### Light System Initialization Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/plugins_lightSystem.js.html Initializes the light system, including creating and compiling shaders for light calculation and composition, and setting up Vertex Array Objects (VAOs) for rendering quads. This setup is crucial before rendering any lighting effects. ```javascript lightSystem.lightShader = glCreateProgram( 'in vec2 vWorldPos;'+ 'out vec4 c;'+ 'void main(){'+ 'float dist=distance(vWorldPos,lightPos);'+ 'float t=clamp((radius-dist)/max(fadeRange,1e-6),0.,1.);'+ 'c=vec4(color.rgb*t*color.a,1.);'+ '}', 'in vec2 vWorldPos; out vec4 c; void main(){ float dist=distance(vWorldPos,lightPos); float t=clamp((radius-dist)/max(fadeRange,1e-6),0.,1.); c=vec4(color.rgb*t*color.a,1.); }' ); // composite shader: fullscreen quad, samples the lightmap lightSystem.compositeShader = glCreateProgram( '#version 300 es\n' + 'precision highp float;'+ 'in vec2 p;'+ 'void main(){'+ 'gl_Position=vec4(p+p-1.,1,1);'+ '}', '#version 300 es\n' + 'precision highp float;'+ 'uniform sampler2D s;'+ 'uniform vec3 iResolution;'+ 'out vec4 c;'+ 'void main(){'+ 'vec2 uv=gl_FragCoord.xy/iResolution.xy;'+ 'c=vec4(texture(s,uv).rgb,1.);'+ '}' ); // VAO for the per-Light quad — reuses the engine unit triangle-strip lightSystem.lightVAO = glContext.createVertexArray(); glContext.bindVertexArray(lightSystem.lightVAO); glContext.bindBuffer(glContext.ARRAY_BUFFER, glGeometryBuffer); const gLight = glContext.getAttribLocation(lightSystem.lightShader, 'g'); glContext.enableVertexAttribArray(gLight); glContext.vertexAttribPointer(gLight, 2, glContext.FLOAT, false, 8, 0); // VAO for the composite fullscreen quad — same buffer, attribute named 'p' lightSystem.compositeVAO = glContext.createVertexArray(); glContext.bindVertexArray(lightSystem.compositeVAO); glContext.bindBuffer(glContext.ARRAY_BUFFER, glGeometryBuffer); const pComp = glContext.getAttribLocation(lightSystem.compositeShader, 'p'); glContext.enableVertexAttribArray(pComp); glContext.vertexAttribPointer(pComp, 2, glContext.FLOAT, false, 8, 0); ``` -------------------------------- ### UISystemPlugin Setup and Debugging Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/plugins_uiSystem.js.html This section covers the initialization of the UI system and how to control its debug drawing. It includes the global object `uiSystem`, the debug flag `uiDebug`, and the function `uiSetDebug` to manage debug modes. ```APIDOC ## Global Variables and Functions ### `uiSystem` * **Type**: `UISystemPlugin` * **Description**: Global UI system plugin object. * **Scope**: `UISystem` ### `uiDebug` * **Type**: `number` * **Description**: Controls UI system debug drawing. `0` for off, `1` for normal, `2` for showing invisible elements. * **Default**: `0` * **Scope**: `UISystem` ### `uiSetDebug(debugMode)` * **Description**: Enables or disables UI system debug drawing. * **Parameters**: * `debugMode` (number|boolean) - The debug mode to set. Can be a number (0, 1, 2) or a boolean (true/false). * **Scope**: `UISystem` ## UISystemPlugin Class ### `constructor(context)` * **Description**: Creates the global UI system object. It asserts that the UI system has not already been initialized. * **Parameters**: * `context` (CanvasRenderingContext2D) - Optional. The canvas rendering context to use. Defaults to `mainContext`. * **Example**: ```javascript // create the ui plugin object new UISystemPlugin; ``` ``` -------------------------------- ### getNavigationDirection Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/UISystem.UISystemPlugin.html Gets the navigation direction input from a gamepad or keyboard. ```APIDOC ## getNavigationDirection() ### Description Get navigation direction from gamepad or keyboard. ### Returns **Type:** number ``` -------------------------------- ### getUp Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/Engine.EngineObject.html Gets the object's up vector, optionally scaled. ```APIDOC ## getUp(scale) ### Description Get this object's up vector. ### Parameters #### Path Parameters - **scale** (number) - Optional - Length of the vector. Defaults to 1. ``` -------------------------------- ### engineInit Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/Engine.html Startup LittleJS engine with your callback functions. This is the main entry point for initializing the game and its core loops. ```APIDOC ## engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost, imageSourcesopt, rootElementopt) ### Description Startup LittleJS engine with your callback functions. ### Parameters #### Required Parameters - **gameInit** (GameInitCallback) - Called once after the engine starts up, can be async for loading. - **gameUpdate** (GameCallback) - Called every frame before objects are updated (60fps), 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. #### Optional Parameters - **imageSources** (Array.) - List of image file paths to preload (e.g., ['player.png', 'tiles.png']). Defaults to []. - **rootElement** (HTMLElement) - Root DOM element to attach canvas to, defaults to document.body. ### Example ```javascript // Basic engine startup engineInit( ()=> { LOG('Game initialized!'); }, // gameInit ()=> { updateGameLogic(); }, // gameUpdate ()=> { updateUI(); }, // gameUpdatePost ()=> { drawBackground(); }, // gameRender ()=> { drawHUD(); }, // gameRenderPost ['tiles.png', 'tilesLevel.png'] // images to load ); ``` ``` -------------------------------- ### Music Instance Source: https://github.com/killedbyapixel/littlejs/blob/main/examples/stress/index.html Creates a music instance using the zzfxm library for background audio. ```javascript // music - Depp Loop const music = new ``` -------------------------------- ### CIRC(x) Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/TweenSystem.html A circular ease-in curve that starts slowly and accelerates. ```APIDOC ## CIRC(x) ### Description A circular ease-in curve that starts slowly and accelerates. ### Parameters #### Path Parameters - **x** (number) - Description: The input value, typically between 0 and 1. ### Returns Type: number ``` -------------------------------- ### Get Rotational Inertia Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/plugins_box2d.js.html Retrieves the rotational inertia of the Box2D body. ```javascript return this.body.GetInertia(); ``` -------------------------------- ### Get Angular Velocity Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/plugins_box2d.js.html Retrieves the angular velocity of the Box2D body. ```javascript return this.body.GetAngularVelocity(); ``` -------------------------------- ### Create and Initialize Vector2 Objects Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/src_engineMath.js.html Demonstrates creating Vector2 objects using the constructor and the helper function vec2. Shows initialization with specific coordinates, default values, and chaining operations. ```javascript let a = vec2(0, 1); // vector with coordinates (0, 1) a = vec2(5); // set a to (5, 5) b = vec2(); // set b to (0, 0) ``` ```javascript let a = new Vector2(2, 3); // vector with coordinates (2, 3) let b = new Vector2; // vector with coordinates (0, 0) let c = vec2(4, 2); // use the vec2 function to make a Vector2 let d = a.add(b).scale(5); // operators can be chained ``` -------------------------------- ### Initialize Game State Source: https://github.com/killedbyapixel/littlejs/blob/main/examples/stress/index.html Sets up the game canvas, camera, collision layer, and initial game variables. ```javascript function gameInit() { // create tile collision ground for objects to collide with tileLayer = new LJS.TileCollisionLayer(vec2(), vec2(99,55)); for (let x = tileLayer.size.x; x--;) tileLayer.setCollisionData(vec2(x,0)); // set things up LJS.setCanvasFixedSize(vec2(1920, 1080)); // 1080p LJS.setCameraScale(20); LJS.setCameraPos(tileLayer.size.scale(.5)); LJS.setCanvasClearColor(rgb(.4,.4,.4)); LJS.setGravity(vec2(0,-.005)); sprites = []; // display stats using a div so it doesn't use canvas rendering document.body.appendChild(statsDisplay = document.createElement('div')); statsDisplay.style = 'position:absolute;width:100%;font-size:3em;text-align:center;font-family:arial;user-select:none;'; } ``` -------------------------------- ### Pause Control Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/src_engine.js.html Functions to get and set the paused state of the game. ```APIDOC ## getPaused ### Description Get if game is paused. ### Return - **boolean** - True if the game is paused, false otherwise. ## setPaused ### Description Set if game is paused. ### Parameters - **isPaused** (boolean) - Optional. Whether to pause the game. Defaults to true. ``` -------------------------------- ### getNavigationOtherDirection Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/UISystem.UISystemPlugin.html Gets the secondary navigation direction input from a gamepad or keyboard. ```APIDOC ## getNavigationOtherDirection() ### Description Get other axis navigation direction from gamepad or keyboard. ### Returns **Type:** number ``` -------------------------------- ### Implement Click to Start and Ball Creation Source: https://github.com/killedbyapixel/littlejs/blob/main/examples/breakoutTutorial/README.md Modifies the game update loop to wait for a mouse click before creating the ball and playing the startup sound. This ensures audio can play in browsers. ```javascript if (ball && ball.pos.y < -1) // if ball is below level { // destroy old ball ball.destroy(); ball = 0; } if (!ball && LJS.mouseWasPressed(0)) // if there is no ball and left mouse is pressed { ball = new Ball(LJS.cameraPos); // create the ball sound_start.play(); // play start sound } ``` -------------------------------- ### getRight Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/Engine.EngineObject.html Gets the object's right vector, optionally scaled. ```APIDOC ## getRight(scale) ### Description Get this object's right vector. ### Parameters #### Path Parameters - **scale** (number) - Optional - Length of the vector. Defaults to 1. ``` -------------------------------- ### Initialize Engine and Game Loop Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/src_engine.js.html Sets up the game environment, ensuring the body element exists and initializing game loop functions. Allows for optional game functions to be passed in. ```javascript ASSERT(isArray(imageSources), 'pass in images as array'); // ensure body exists for minimal HTML where the script runs before is parsed if (!document.body) document.documentElement.appendChild(document.createElement('body')); rootElement ||= document.body; // allow passing in empty functions gameInit ||= ()=>{}; gameUpdate ||= ()=>{}; gameUpdatePost ||= ()=>{}; gameRender ||= ()=>{}; gameRenderPost ||= ()=>{}; ``` -------------------------------- ### getMotorTorque Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/Box2D.Box2dWheelJoint.html Gets the motor torque applied for a given time step. ```APIDOC ## getMotorTorque ### Description Gets the motor torque for a time step. ### Returns - **number**: The motor torque. ### Source * [plugins/box2d.js](plugins_box2d.js.html#line1361) ``` -------------------------------- ### playMusic Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/src_engineAudio.js.html Plays a music track. It loops by default and can be set to start paused. ```APIDOC ## playMusic ### Description Plays a music track that loops by default. ### Parameters * **volume** (number, optional) - Volume to play the music at. Defaults to 1. * **loop** (boolean, optional) - Should the music loop? Defaults to true. * **paused** (boolean, optional) - Should the music start paused? Defaults to false. ### Returns * **SoundInstance** - The sound instance created for the music track. ``` -------------------------------- ### Create Video Player UI Object Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/plugins_uiSystem.js.html Example of creating a video player UI object with specified position, size, video source, and optional autoplay/loop settings. ```javascript // Create a video player UI object const video = new VideoPlayerUIObject(vec2(400, 300), vec2(320, 240), 'video.mp4', true); video.play(); ``` -------------------------------- ### Transformations and Vectors Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/src_engineObject.js.html Methods for getting directional vectors and managing object transformations. ```APIDOC ## getUp ### Description Get this object's up vector. ### Parameters * **scale** (number, optional) - length of the vector ### Return * **Vector2** ## getRight ### Description Get this object's right vector. ### Parameters * **scale** (number, optional) - length of the vector ### Return * **Vector2** ``` -------------------------------- ### Create and Configure Video Player Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/plugins_uiSystem.js.html Initializes a video player element, setting its source, loop, volume, and muted state. Appends the video element to the document body and optionally starts playback. ```javascript constructor(pos, size, src, autoplay=false, loop=false, volume=1) { super(pos, size || vec2()); ASSERT(isStringLike(src), 'video src must be a string'); ASSERT(isNumber(volume), 'video volume must be a number'); this.color = BLACK; // default to black background this.cornerRadius = 0; // default to no corner radius /** @property {number} - The video volume */ this.volume = volume; // create video element /** @property {HTMLVideoElement} - The video player */ this.video = document.createElement('video'); this.video.loop = loop; this.video.volume = clamp(volume * soundVolume); this.video.muted = !soundEnable; this.video.style.display = 'none'; this.video.src = src; document.body.appendChild(this.video); autoplay && this.play(); } ``` -------------------------------- ### getCameraSize Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/Draw.html Gets the current size of the camera window in world space units. ```APIDOC ## getCameraSize() ### Description Get the size of the camera window in world space. ### Method (static) ### Returns: Type: Vector2 - A Vector2 object representing the camera's dimensions in world space. ``` -------------------------------- ### Create UISystemPlugin Instance Source: https://github.com/killedbyapixel/littlejs/blob/main/docs/UISystem.UISystemPlugin.html Instantiate the global UI system object. This is typically done once to initialize the UI system. ```javascript new UISystemPlugin; ```