### Install http-server Globally Source: https://kaplayjs.com/docs/guides/install Install the http-server package globally to serve static files. This is required for the zero-bundler installation method. ```bash npm install --global http-server ``` -------------------------------- ### Start Ngrok Tunnel Source: https://kaplayjs.com/docs/guides/how-to-make-a-multiplayer-game-with-colyseus-and-kaplay Navigate to the client directory and run the command to start the Ngrok tunnel for testing. Ensure you have registered an account on ngrok.com. ```bash cd client npm run ngrok ``` -------------------------------- ### Start Cloudflared Tunnel Source: https://kaplayjs.com/docs/guides/how-to-make-a-multiplayer-game-with-colyseus-and-kaplay Navigate to the client directory and run the command to start the Cloudflared tunnel for testing. ```bash cd client npm run cloudflared ``` -------------------------------- ### Start KAPLAY Development Server Source: https://kaplayjs.com/docs/guides/install Navigate to your game directory and run this command to start the local development server. Your game will be accessible at https://localhost:5173. ```bash cd myGame && npm run dev ``` -------------------------------- ### Install experimental KAPLAY version Source: https://kaplayjs.com/docs/guides/ai Use this command to install the latest development version from GitHub for experimental features. ```bash npm i github:kaplayjs/kaplay ``` -------------------------------- ### Install KAPLAY package Source: https://kaplayjs.com/docs/guides/migration-kaplay Use npm to install the KAPLAY package. ```bash npm install kaplay@3001 ``` -------------------------------- ### Start API Source: https://kaplayjs.com/docs/api/Edge API related to game startup and initialization. ```APIDOC ## Start API ### Description API related to game startup and initialization. ### Functions - `kaplay()`: Initializes Kaplay. - `quit()`: Quits the game. - `KAPLAYOpt`: Options for Kaplay initialization. ``` -------------------------------- ### Start API Source: https://kaplayjs.com/docs/api/AppGfxCtx Functions for starting and quitting the KaplayJS application. ```APIDOC ## Start API ### Description Functions for starting and quitting the KaplayJS application. ### Methods - `kaplay()`: Starts the KaplayJS engine. - `quit()`: Quits the KaplayJS engine. - `KAPLAYOpt()`: Options for initializing KaplayJS. ``` -------------------------------- ### Start Development Servers Source: https://kaplayjs.com/docs/guides/how-to-make-a-multiplayer-game-with-colyseus-and-kaplay Commands to initialize and run the Colyseus server and the KAPLAY game client. ```bash cd server npm install npm start ``` ```bash cd client npm install npm start ``` -------------------------------- ### Install esbuild for Bundling Source: https://kaplayjs.com/docs/guides/install Install esbuild, a fast bundler, to package your KAPLAY project. This is one of many bundler options available. ```bash npm install esbuild ``` -------------------------------- ### Install KAPLAY via NPM Source: https://kaplayjs.com/docs/guides/install Install the KAPLAY library using npm for custom Node.js projects. This requires a bundler to use KAPLAY in your project. ```bash npm install kaplay ``` -------------------------------- ### kaplay() Source: https://kaplayjs.com/docs/api/reference Initializes the KAPLAY context, which serves as the starting point for all KAPLAY games. ```APIDOC ## kaplay(gopt?: KAPLAYOpt) ### Description Initializes the KAPLAY context. The starting point of all KAPLAY games. ### Parameters #### Request Body - **width** (number) - Optional - Width of game. - **height** (number) - Optional - Height of game. - **scale** (number) - Optional - Pixel scale / size. - **stretch** (boolean) - Optional - If stretch canvas to container when width and height is specified. - **letterbox** (boolean) - Optional - When stretching if keep aspect ratio and leave black bars on remaining spaces. - **debug** (boolean) - Optional - If register debug buttons (default true). - **debugKey** (Key) - Optional - Key that toggles debug mode. - **font** (string) - Optional - Default font (defaults to "monospace"). - **pixelDensity** (number) - Optional - Device pixel scale (defaults to 1). - **crisp** (boolean) - Optional - Disable antialias and enable sharp pixel display. - **canvas** (HTMLCanvasElement) - Optional - The canvas DOM element to use. - **root** (HTMLElement) - Optional - The container DOM element to insert the canvas. - **background** (RGBValue | RGBAValue | string) - Optional - Background color. - **texFilter** (TexFilter) - Optional - Default texture filter. - **logMax** (number) - Optional - How many log messages can there be on one screen (default 8). - **logTime** (number) - Optional - How many seconds log messages stay on screen (default 4). - **hashGridSize** (number) - Optional - Size of the spatial hash grid for collision detection (default 64). - **touchToMouse** (boolean) - Optional - If translate touch events as mouse clicks (default true). - **loadingScreen** (boolean) - Optional - If KAPLAY should render a default loading screen (default true). - **backgroundAudio** (boolean) - Optional - If pause audio when tab is not active (default false). - **gamepads** (Record) - Optional - Custom gamepad definitions. - **buttons** (TButtonDef) - Optional - Defined buttons for input binding. - **maxFPS** (number) - Optional - Limit framerate to an amount per second. - **focus** (boolean) - Optional - If focus on the canvas on start (default true). - **global** (boolean) - Optional - If import all KAPLAY functions to global (default true). - **plugins** (TPlugin) - Optional - List of plugins to import. - **burp** (boolean) - Optional - Enter burp mode. - **tagsAsComponents** (boolean) - Optional - Make component's id be added as tags. - **spriteAtlasPadding** (number) - Optional - Padding used when adding sprites to texture atlas. ### Request Example { "width": 320, "height": 240, "font": "sans-serif" } ``` -------------------------------- ### Core Initialization and Control Source: https://kaplayjs.com/docs/api/ctx/pos Functions for starting and controlling the KaplayJS game instance. ```APIDOC ## Core Initialization and Control This section covers the fundamental functions for starting and managing the KaplayJS game. ### Initialization - **kaplay(options)**: Initializes the KaplayJS engine. This is typically the first function called. ### Game Control - **quit()**: Shuts down the KaplayJS engine and cleans up resources. ### Options - **KAPLAYOpt**: Type definition for options passed to the `kaplay()` function. ``` -------------------------------- ### Core Game Initialization and Control Source: https://kaplayjs.com/docs/api/Anchor APIs for starting, quitting, and configuring the Kaplay game instance. ```APIDOC ## Core Game Initialization and Control ### Description APIs for starting, quitting, and configuring the Kaplay game instance. ### Methods - `kaplay()`: Initializes the Kaplay game. - `quit()`: Terminates the Kaplay game. - `KAPLAYOpt()`: Sets global options for Kaplay. ``` -------------------------------- ### Install KAPLAY Next Version Source: https://kaplayjs.com/docs/guides/migration-4000 Update your KAPLAY library to the next version using npm. ```bash npm install kaplay@next ``` -------------------------------- ### Network Address Output Source: https://kaplayjs.com/docs/guides/how-to-make-a-multiplayer-game-with-colyseus-and-kaplay Example of the network address provided by the development server. ```text -> Network: http://192.168.1.2:5173/ ``` -------------------------------- ### Initialize KAPLAY Documentation Repository Source: https://kaplayjs.com/docs/guides/contributor-guide-on-guides Commands to clone the repository, initialize submodules, and start the development server. ```bash git clone https://github.com/kaplayjs/kaplay-site.git git submodule init git submodule update pnpm ci pnpm dev ``` -------------------------------- ### Get All Game Objects Source: https://kaplayjs.com/docs/guides/game_objects Retrieve all game objects in the scene using `get('*')`. You can also filter by tag, for example, `get('friend')`. ```javascript // Get a list with all game objects const allObjs = get("* "); debug.log(allObjs.length); // Get a list of friends tagged objects and iterate over them get("friend").forEach((friend) => { debug.log(friend.sprite, "is here!"); }); ``` -------------------------------- ### Clone the KAPLAY Colyseus Quickstart Repository Source: https://kaplayjs.com/docs/guides/how-to-make-a-multiplayer-game-with-colyseus-and-kaplay Use this command to download the starter template for a new multiplayer project. ```bash git clone https://github.com/colyseus/kaplay.git kaplay-colyseus ``` -------------------------------- ### Info API - getTime Source: https://kaplayjs.com/docs/api/ctx/getCursor Get the total elapsed time since the game started. ```APIDOC ## GET time ### Description Get the total elapsed time since the game started. ### Method GET ### Endpoint /info/time ### Parameters None ### Request Example None ### Response #### Success Response (200) - **time** (number) - The total elapsed time. #### Response Example { "time": 120.5 } ``` -------------------------------- ### Build Game Client Source: https://kaplayjs.com/docs/guides/how-to-make-a-multiplayer-game-with-colyseus-and-kaplay Navigate to the client directory and run the build command to create a production-ready build of your game. The build output will be in the /client/dist folder. ```bash cd client # Linux npm run build # Windows npx vite build ``` -------------------------------- ### Initialize KAPLAY Context Source: https://kaplayjs.com/docs/api/kaplay Demonstrates starting the engine with default settings, custom options, and how to manage global namespace pollution. ```javascript // Start KAPLAY with default options (will create a fullscreen canvas under ) kaplay() // Init with some options kaplay({ width: 320, height: 240, font: "sans-serif", canvas: document.querySelector("#mycanvas"), background: [ 0, 0, 255, ], }) // All KAPLAY functions are imported to global after calling kaplay() add() onUpdate() onKeyPress() vec2() // If you want to prevent KAPLAY from importing all functions to global and use a context handle for all KAPLAY functions const k = kaplay({ global: false }) k.add(...) k.onUpdate(...) k.onKeyPress(...) k.vec2(...) ``` -------------------------------- ### Starting Development Server with Host Access Source: https://kaplayjs.com/docs/guides/how-to-make-a-multiplayer-game-with-colyseus-and-kaplay Expose the development server to the local network to allow access from other devices. ```bash cd client # Linux npm run start -- --host # Windows npm run start -- -- --host ``` -------------------------------- ### Define Guide Frontmatter Source: https://kaplayjs.com/docs/guides/contributor-guide-on-guides Standard YAML frontmatter required for all MDX guide files. ```yaml --- title: Creating Guides # The title, it appears in the sidebar description: You shouldn't see this # Description for metadata version: "4000" # Don't use it unless the guide is only for v4000 url: contributor-guide-on-guides # The url order: "misc-4" # The order string, just follow the others in the same category hidden: true # Hide it noads: true # Disable ads (used in Contributors pages) --- ``` -------------------------------- ### Configure and use layers Source: https://kaplayjs.com/docs/api/ctx/layers Initialize the game layers and demonstrate adding objects to specific layers. ```javascript setLayers(["bg", "obj", "ui"], "obj") // no layer specified, will be added to "obj" add([ sprite("bean"), ]); // add to "bg" layer add([ sprite("bg"), layer("bg"), ]); ``` -------------------------------- ### Install @kaplayjs/crew Package Source: https://kaplayjs.com/docs/guides/crew Use npm to install the KAPLAY Crew package. This is the first step before loading the plugin. ```bash npm i @kaplayjs/crew ``` -------------------------------- ### onTouchStart Source: https://kaplayjs.com/docs/api/ctx/onTouchStart Registers an event listener for when a touch input begins. It accepts a callback function that will be executed upon touch start. ```APIDOC ## onTouchStart ### Description Registers an event that runs when a touch starts. ### Method `onTouchStart` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **action** ( (pos: Vec2, t: Touch) => void) - Required - The function to run when the event is triggered. ### Request Example ```json { "action": "(pos, t) => console.log('Touch started at', pos)" } ``` ### Response #### Success Response (200) - **KEventController** (object) - The event controller, which can be used to cancel the event. #### Response Example ```json { "eventController": "{ cancel: () => void }" } ``` ``` -------------------------------- ### Get Children of a Game Object Source: https://kaplayjs.com/docs/guides/game_objects Retrieve children of a game object using `obj.get()`. Use the `recursive: true` option to get all descendants. ```javascript bag.get("* "); // Get all children [2] // We can pass recursive: true for getting descendants too bag.get("favorite", { recursive: true }); // The favorite! [superMiniBag] ``` -------------------------------- ### Serve Static Files with http-server Source: https://kaplayjs.com/docs/guides/install Run this command in your project directory to start a local server for serving static files. This is necessary when using KAPLAY via CDN. ```bash http-server ``` -------------------------------- ### Get Center Point of View Source: https://kaplayjs.com/docs/api/ctx/center Use `center()` to get the center point of the view. This is useful for positioning elements relative to the screen center. ```javascript // add bean to the center of the screen add([ sprite("bean"), pos(center()), // ... ]) ``` -------------------------------- ### Initialize and Play Video Component Source: https://kaplayjs.com/docs/guides/video Use the video component to add videos for intros or cut-scenes. Ensure to call `.play()` after initialization to start playback. ```javascript const intro = add([ pos(200, 100), // Where to place the video video("intro.mp4"), ]); intro.play(); ``` -------------------------------- ### Get Delta Time in kaplayjs Source: https://kaplayjs.com/docs/api/ctx/dt Use `dt()` to get the time elapsed since the last frame. This is useful for frame-rate independent movement or animations. ```javascript // rotate bean 100 deg per second bean.onUpdate(() => { bean.angle += 100 * dt() }) ``` -------------------------------- ### Configure and Initialize Particle Emitter Source: https://kaplayjs.com/docs/guides/particles Shows the full setup of a particle emitter using the particles component, including sprite loading and configuration options. ```javascript // load the sprite, and wait for the sprite to fully load before making the particle emitter // NOTE: this is the easiest way to ensure your sprites have been loaded, but not the best loadSprite("bean", "./sprites/bean.png").then((data) => { // Fun fact: the data parameter passed from the promise is the same as getSprite().data let loadedSpriteData = getSprite("bean").data; let particleEmitter = add([ pos(center()), particles( { max: 20, // the max amount of particles generated from this emitter at one time lifeTime: [2, 5], // how long the particles last before being destroyed speed: [50, 100], // how fast the particles are moving acceleration: [vec2(0), vec2(0, -10)], // changes the speed of the particle over its lifetime damping: [0, 0.5], // slows down the particle over its lifetime angle: [0, 360], // the rotation of each particle angularVelocity: [0, 100], // how fast each particle should be rotating scales: [1.0, 0.5, 0.0], // how large the particle is over its lifetime colors: [RED, GREEN, BLUE], // the color of the particle over its lifetime opacities: [1.0, 0.0], // the opacity of the particle over its lifetime texture: loadedSpriteData.tex, // texture of the sprite quads: loadedSpriteData.frames, // to tell whe emitter what frames of the sprite to use }, { shape: new Rect(vec2(0), 32, 32), // the area where particles should be emitted from (can be empty) lifetime: 5, // how long the emitter should last rate: 5, // the rate at which particles are emitted direction: 0, // the direction where particles should be traveling spread: 45, // variance in the direction where particles should be traveling }, ), ]); // .onEnd is called when the emitter's lifetime (in this example 5 seconds), has expired. particleEmitter.onEnd(() => { destroy(particleEmitter); }); // Emit Particles at runtime particleEmitter.emit(5); // Wait 1 second, then emit more wait(1, () => { particleEmitter.emit(15); }); }); ``` -------------------------------- ### Define puck size and starting position Source: https://kaplayjs.com/docs/guides/how-to-make-a-multiplayer-game-with-colyseus-and-kaplay Defines constants for the puck's size and its starting position. `startPos` is a function to ensure the center is recalculated if needed. ```typescript const size = 48; const startPos = () => (k.center().sub(0, 6)); ``` -------------------------------- ### Correctly Initialize KAPLAY with Scenes Source: https://kaplayjs.com/docs/guides/scenes To enable scene switching and return capabilities, define all necessary scenes first, then use `go()` to navigate between them. ```javascript k.scene("mark", () => { k.add([sprite("mark")]); }); k.scene("bean", () => { k.add([sprite("bean")]); }); k.go("bean"); // we can do go("mark") later! :D ``` -------------------------------- ### initAudio Function Source: https://kaplayjs.com/docs/api/initAudio Initializes the audio system and returns the AudioContext and master GainNode for audio manipulation. ```APIDOC ## initAudio ### Description Initializes the audio system for the project. Returns an object containing the AudioContext and the master GainNode. ### Returns - **ctx** (AudioContext) - The Web Audio API context. - **masterNode** (GainNode) - The master gain node used for controlling global volume. ``` -------------------------------- ### Load a new loader to wait for before starting the game Source: https://kaplayjs.com/docs/api/ctx/load Use this function to add a new loader that must complete before the game starts. It accepts a Promise that resolves with the asset data. ```javascript load(new Promise((resolve, reject) => { // anything you want to do that stalls the game in loading state resolve("ok") })) ``` -------------------------------- ### Layers Configuration Source: https://kaplayjs.com/docs/api/ctx/Point APIs for setting and getting layers. ```APIDOC ## Layers API ### Description Manages the configuration and retrieval of layers. ### Methods - `setLayers(layers)` - `getLayers()` - `getDefaultLayer()` ``` -------------------------------- ### randSeed Source: https://kaplayjs.com/docs/api/ctx/randSeed Get or set the random number generator seed. ```APIDOC ## randSeed(seed?: number): number ### Description Get or set the random number generator seed. ### Parameters #### Request Body - **seed** (number) - Optional - The seed to set. ### Request Example randSeed(Date.now()) ### Response - **returns** (number) - The new seed. ``` -------------------------------- ### Full Game Implementation Source: https://kaplayjs.com/docs/guides/creating_your_first_game A complete example integrating scene management, physics, collision, and score tracking. ```javascript import kaplay from "kaplay"; import "kaplay/global"; // comment if you want to use the k. prefix const FLOOR_HEIGHT = 48; const JUMP_FORCE = 800; const SPEED = 480; // initialize context kaplay(); // load assets loadSprite("bean", "sprites/bean.png"); scene("game", () => { // define gravity setGravity(1600); // add a game object to screen const player = add([ // list of components sprite("bean"), pos(80, 40), area(), body(), ]); // floor add([ rect(width(), FLOOR_HEIGHT), outline(4), pos(0, height()), anchor("botleft"), area(), body({ isStatic: true }), color(127, 200, 255), ]); function jump() { if (player.isGrounded()) { player.jump(JUMP_FORCE); } } // jump when user press space onKeyPress("space", jump); onMousePress(jump); function spawnTree() { // add tree obj add([ rect(48, rand(32, 96)), area(), body({isStatic: true}), outline(4), pos(width(), height() - FLOOR_HEIGHT), anchor("botleft"), color(255, 180, 255), move(LEFT, SPEED), "tree", ]); // wait a random amount of time to spawn next tree wait(rand(0.5, 1.5), spawnTree); } // start spawning trees spawnTree(); // lose if player collides with any game obj with tag "tree" player.onCollide("tree", () => { // go to "lose" scene and pass the score go("lose", score); burp(); addKaboom(player.pos); }); // keep track of score let score = 0; const scoreLabel = add([text(score), pos(24, 24)]); // increment score every frame onUpdate(() => { score++; scoreLabel.text = score; }); }); scene("lose", (score) => { add([text("Game Over"), pos(center()), anchor("center")]); // display score add([ text(score), pos(width() / 2, height() / 2 + 80), scale(2), anchor("center"), ]); // go back to game when space is pressed onKeyPress("space", () => go("game")); onMousePress(() => go("game")); }); go("game"); ``` -------------------------------- ### GET isCursorLocked Source: https://kaplayjs.com/docs/api/ctx/isCursorLocked Retrieves the current lock status of the cursor. ```APIDOC ## GET isCursorLocked ### Description Returns the current lock state of the cursor. ### Method GET ### Endpoint isCursorLocked() ### Response #### Success Response (200) - **returns** (boolean) - true if the cursor is locked, false otherwise. ``` -------------------------------- ### GET fixedDt Source: https://kaplayjs.com/docs/api/ctx/fixedDt Retrieves the fixed delta time value. ```APIDOC ## GET fixedDt ### Description Returns the fixed delta time since the last frame as a number. ### Method GET ### Endpoint fixedDt() ### Response #### Success Response (200) - **value** (number) - The fixed delta time value. ``` -------------------------------- ### Initialize Kaplay Context Source: https://kaplayjs.com/docs/guides/creating_your_first_game Call this function to start a new Kaplay game instance. It sets up the game canvas and basic rendering. ```javascript kaplay(); ``` -------------------------------- ### Info API - getHeight Source: https://kaplayjs.com/docs/api/ctx/getCursor Get the height of the game canvas. ```APIDOC ## GET height ### Description Get the height of the game canvas. ### Method GET ### Endpoint /info/height ### Parameters None ### Request Example None ### Response #### Success Response (200) - **height** (number) - The height of the canvas. #### Response Example { "height": 600 } ``` -------------------------------- ### Initialize a New Repository Source: https://kaplayjs.com/docs/guides/how-to-make-a-multiplayer-game-with-colyseus-and-kaplay Commands to remove the existing git history and initialize a fresh repository for your project. ```bash # Linux (Bash) cd kaplay-colyseus; rm -rf .git; git init; git add .; git commit -m "Init commit" ``` ```powershell # Windows (PowerShell) cd kaplay-colyseus; rm -r -Force .git; git init; git add .; git commit -m "Init commit" ``` ```cmd # Windows (CMD) cd kaplay-colyseus && rmdir /s /q .git && git init && git add . && git commit -m "Init commit" ``` -------------------------------- ### Info API - getWidth Source: https://kaplayjs.com/docs/api/ctx/getCursor Get the width of the game canvas. ```APIDOC ## GET width ### Description Get the width of the game canvas. ### Method GET ### Endpoint /info/width ### Parameters None ### Request Example None ### Response #### Success Response (200) - **width** (number) - The width of the canvas. #### Response Example { "width": 800 } ``` -------------------------------- ### kaplay() - Initialization Source: https://kaplayjs.com/docs/api/kaplay Initializes the KAPLAY context, which is the starting point for all KAPLAY games. It can be called with default options or custom configurations. ```APIDOC ## kaplay() ### Description Initializes the KAPLAY context. This is the entry point for all KAPLAY games. It can create a fullscreen canvas or attach to a specified DOM element. ### Method `kaplay(options?: KAPLAYOpt): KAPLAYCtx` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (KAPLAYOpt) - Optional - Configuration object for KAPLAY initialization. - **width** (number) - Optional - The width of the canvas. - **height** (number) - Optional - The height of the canvas. - **font** (string) - Optional - The default font family for text. - **canvas** (HTMLElement) - Optional - The DOM element to attach the canvas to. - **background** (Color) - Optional - The background color of the canvas. - **global** (boolean) - Optional - If true, all KAPLAY functions are imported to the global scope. Defaults to true. ### Request Example ```javascript // Start KAPLAY with default options kaplay() // Init with some options kaplay({ width: 320, height: 240, font: "sans-serif", canvas: document.querySelector("#mycanvas"), background: [ 0, 0, 255, ], }) // Initialize without global functions const k = kaplay({ global: false }) k.add(...) ``` ### Response #### Success Response (KAPLAYCtx) - **KAPLAYCtx** - The KAPLAY context object, providing access to all KAPLAY functions if `global` is set to `false`. #### Response Example ```javascript // If global is true, no explicit return value is needed for context // If global is false, k will be the KAPLAY context const k = kaplay({ global: false }) console.log(typeof k.add) // "function" ``` ``` -------------------------------- ### Create KAPLAY Project with npx Source: https://kaplayjs.com/docs/guides/install Use this command to generate a new KAPLAY project with the recommended structure. Ensure Node.js is installed. ```bash npx create-kaplay myGame ``` -------------------------------- ### Input - mousePos Source: https://kaplayjs.com/docs/api/ctx/Quad Gets the current position of the mouse cursor. ```APIDOC ## mousePos ### Description Gets the current mouse position. ### Type `typeof Vec2` ### Group Input ``` -------------------------------- ### Scale Component Source: https://kaplayjs.com/docs/api/reference Functions to set and get the scale of a game object. ```APIDOC ## scale **( x: number, y: number): ScaleComp** Set the scale of a Game Object. `param` x- The x scale to set. `param` y- The y scale to set. ``` // scale uniformly with one value add([ sprite("bean"), scale(3), ]); // scale with x & y values. In this case, scales more horizontally. add([ sprite("bean"), scale(3, 1), ]); // scale with vec2(x,y). bean.scale = vec2(2,4); ``` `returns` The scale comp. `since` v2000.0 `group` Components ``` ```APIDOC ## scale **( xy: number): ScaleComp** ``` ```APIDOC ## scale **( s: Vec2): ScaleComp** ``` ```APIDOC ## scale **(): ScaleComp** ``` -------------------------------- ### go Source: https://kaplayjs.com/docs/api/reference Navigates to a specified scene, passing optional arguments to the scene callback. ```APIDOC ## go(name, args) ### Description Go to a scene, passing all rest args to scene callback. ### Parameters #### Path Parameters - **name** (SceneName) - Required - The scene name. - **args** (any) - Optional - The rest args to pass to the scene callback. ``` -------------------------------- ### Initialize Audio Context Source: https://kaplayjs.com/docs/api/initAudio Initializes the audio system, providing access to the AudioContext and master GainNode. ```javascript initAudio: () => { ``` ```typescript ctx: AudioContext ``` ```typescript masterNode: GainNode ``` -------------------------------- ### Position Component Source: https://kaplayjs.com/docs/api/reference Functions to set and get the position of a game object. ```APIDOC ## pos **( x: number, y: number): PosComp** Set the position of a Game Object. `param` x- The x position to set. `param` y- The y position to set. ``` // This game object will draw a "bean" sprite at (100, 200) add([ pos(100, 200), sprite("bean"), ]); ``` `returns` The position comp. `since` v2000.0 `group` Components ``` ```APIDOC ## pos **( xy: number): PosComp** ``` ```APIDOC ## pos **( p: Vec2): PosComp** ``` ```APIDOC ## pos **(): PosComp** ``` -------------------------------- ### initGfx Function Source: https://kaplayjs.com/docs/api/reference Initializes the graphics context. ```APIDOC ## initGfx ### Description Initializes the graphics context. ### Properties - **gl** (WebGLRenderingContext) - **opts** ({ texFilter?: TexFilter }) - **onDestroy** ((action: () => unknown) => void) - **destroy** (() => void) - **pushTexture2D** ((item: WebGLTexture) => void) - **popTexture2D** (() => void) - **pushArrayBuffer** ((item: WebGLBuffer) => void) - **popArrayBuffer** (() => void) - **pushElementArrayBuffer** ((item: WebGLBuffer) => void) - **popElementArrayBuffer** (() => void) - **pushFramebuffer** ((item: WebGLFramebuffer) => void) - **popFramebuffer** (() => void) - **pushRenderbuffer** ((item: WebGLRenderbuffer) => void) - **popRenderbuffer** (() => void) - **pushViewport** ((item: { x: number, y: number, w: number, h: number }) => void) - **popViewport** (() => void) - **pushProgram** ((item: WebGLProgram) => void) - **popProgram** (() => void) - **setVertexFormat** ((fmt: VertexFormat) => void) ``` -------------------------------- ### get Source: https://kaplayjs.com/docs/api/reference Retrieve a list of game objects based on specific tags. ```APIDOC ## get ### Description Get a list of all game objs with certain tag. ### Parameters #### Path Parameters - **tag** (Tag | Tag[]) - Required - The tag to search for. Use "*" to get all objects. - **opts** (GetOpt) - Optional - Additional options. ### Response - **GameObj[]** - A list of game objects that have the tag. ``` -------------------------------- ### Game Obj API - get Source: https://kaplayjs.com/docs/api/ctx/height Retrieves a game object by its ID. ```APIDOC ## GET get ### Description Get a game object by its ID. ### Method GET ### Endpoint /gameObjects/get ### Query Parameters - **id** (string) - Required - The ID of the game object to retrieve. ### Request Example None ### Response #### Success Response (200) - **gameObject** (GameObject) - The requested game object. #### Response Example ```json { "gameObject": { "id": "player1", "pos": {"x": 100, "y": 100}, "sprite": "playerSprite" } } ``` ``` -------------------------------- ### Info API - getGamepads Source: https://kaplayjs.com/docs/api/ctx/getCursor Get a list of connected gamepad objects. ```APIDOC ## GET getGamepads ### Description Get a list of connected gamepad objects. ### Method GET ### Endpoint /info/getGamepads ### Parameters None ### Request Example None ### Response #### Success Response (200) - **gamepads** (array) - An array of gamepad objects. #### Response Example { "gamepads": [ { "id": "Gamepad (Standard Gamepad)", "connected": true } ] } ``` -------------------------------- ### initAppState Source: https://kaplayjs.com/docs/api/reference Initializes the application state, including input mapping, timing, and FPS tracking. ```APIDOC ## initAppState ### Description Configures the application state, including canvas reference, input button mappings, and timing variables. ### Parameters - **opt** (Object) - Required - Configuration object containing canvas, pixelDensity, and maxFPS. ### Response - **canvas** (HTMLCanvasElement) - The target rendering canvas. - **fpsCounter** (FPSCounter) - The frame rate tracking utility. - **time** (number) - Current game time. - **dt** (number) - Delta time since last frame. ``` -------------------------------- ### Create and add a game object Source: https://kaplayjs.com/docs/api/ctx/make Use make to initialize a game object with components, then add it to the scene to enable rendering. ```javascript const label = make([ rect(100, 20), ]); // Add a new text to the label label.add([ text("Hello, world!"), ]); // Add game object to the scene // Now it will render add(label); ``` -------------------------------- ### Info API - getDt Source: https://kaplayjs.com/docs/api/ctx/getCursor Get the time delta for the current frame. ```APIDOC ## GET dt ### Description Get the time delta for the current frame. ### Method GET ### Endpoint /info/dt ### Parameters None ### Request Example None ### Response #### Success Response (200) - **dt** (number) - The time delta. #### Response Example { "dt": 0.016 } ``` -------------------------------- ### Info and Configuration Source: https://kaplayjs.com/docs/api/TweenController Accessing game information and configuring settings. ```APIDOC ## Info and Configuration ### Description Provides access to game information and allows configuration of certain settings. ### Properties - `width: number` - `height: number` - `dt: number` (delta time) - `time: number` (total elapsed time) - `VERSION: string` ### Functions #### `setBackground(color: Color): void` Sets the background color of the game canvas. #### `setCursor(cursor: string): void` Sets the mouse cursor style. #### `setFullscreen(enabled: boolean): void` Toggles fullscreen mode. #### `canvas: HTMLCanvasElement` Reference to the game canvas element. ``` -------------------------------- ### Info - height Source: https://kaplayjs.com/docs/api/ctx/Quad Gets the current height of the game canvas or window. ```APIDOC ## height ### Description Gets the game canvas height. ### Type `number` ### Group Info ``` -------------------------------- ### Info - width Source: https://kaplayjs.com/docs/api/ctx/Quad Gets the current width of the game canvas or window. ```APIDOC ## width ### Description Gets the game canvas width. ### Type `number` ### Group Info ``` -------------------------------- ### Event Listening Patterns Source: https://kaplayjs.com/docs/guides/events Demonstrates different ways to listen for global, object-specific, and custom events. ```javascript // a global event onUpdate(() => {}); // an object event obj.onUpdate(() => {}); // a custom event obj.on("hi", () => {}); ``` -------------------------------- ### GET renderArea Source: https://kaplayjs.com/docs/api/RectComp Retrieves the current rendering area dimensions and position. ```APIDOC ## GET renderArea ### Description Returns the current rendering area as a Rect object. ### Method GET ### Endpoint renderArea() ### Response #### Success Response (200) - **Rect** (object) - The rectangle representing the current render area. ``` -------------------------------- ### initApp Source: https://kaplayjs.com/docs/api/reference Initializes the KaplayJS application with the provided configuration options and returns an application controller. ```APIDOC ## initApp ### Description Initializes the application environment, setting up the canvas, input handling, and game loop configuration. ### Parameters #### Request Body - **canvas** (HTMLCanvasElement) - Required - The target canvas element. - **touchToMouse** (boolean) - Optional - Whether to map touch events to mouse events. - **gamepads** (Record) - Optional - Gamepad definitions. - **pixelDensity** (number) - Optional - The pixel density for the canvas. - **maxFPS** (number) - Optional - The maximum frames per second. - **buttons** (ButtonsDef) - Optional - Custom button definitions. ### Response #### Success Response (200) - **state** (Object) - The current application state including input states, timing, and canvas info. - **dt** (Function) - Returns the delta time. - **run** (Function) - Starts the game loop with fixedUpdate and update callbacks. - **quit** (Function) - Stops the application. - **setFullscreen** (Function) - Toggles fullscreen mode. - **isKeyDown** (Function) - Checks if a specific key is currently held down. ``` -------------------------------- ### screenArea Source: https://kaplayjs.com/docs/api/AreaComp Get the geometry data for the collider in screen coordinate space. ```APIDOC ## screenArea ### Description Get the geometry data for the collider in screen coordinate space. ### Method (No HTTP method specified, likely a function call) ### Endpoint (Not applicable, likely a method within a game object context) ### Parameters None ### Request Example ```javascript // Assuming 'obj' is a game object with a collider const screenCollider = obj.screenArea(); ``` ### Response #### Success Response (Polygon) - **geometry** (Polygon) - The geometry data in screen coordinates. #### Response Example ```json { "type": "polygon", "vertices": [ {"x": 100, "y": 50}, {"x": 200, "y": 50}, {"x": 200, "y": 150}, {"x": 100, "y": 150} ] } ``` ```