KAPLAY Documentation

repository·master·Indexed 21 days ago

https://github.com/kaplayjs/kaplay

KAPLAY is a fun-first, 2D game library for JavaScript and TypeScript designed for speed and simplicity. It utilizes a component-based architecture to build game objects and behaviors, featuring a comprehensive API for input handling (keyboard, mouse, gamepad, touch), asset loading via loadSprite(), and a flexible game loop with support for both fixed and variable update steps.

Tokens
10.4K
Snippets
7
Records
62
Agent score
83%

What's inside KAPLAY

  1. How game objects and behaviors work in KAPLAY

    master

    KAPLAY uses a component-based architecture. You build game objects by passing an array of components to add(). Behaviors are handled through an imperative syntax using event listeners and update loops:

    • Component-based properties: Components like area() provide methods like .onCollide(). Components like health() provide properties like .hp.
    • Lifecycle and Input: Use onUpdate() for frame-by-frame logic, onUpdate(tag, callback) to run logic for all objects with a specific tag, and onKeyDown(key, callback) for input handling.
    • Object Management: Use destroy(obj) to remove an object from the scene.
    // .onCollide() comes from "area" component
    player.onCollide("enemy", () => {
        // .hp comes from "health" component
        player.hp--;
    });
    
    // check fall death
    player.onUpdate(() => {
        if (player.pos.y >= height()) {
            destroy(player);
        }
    });
    
    // All objects with tag "enemy" will move to the left
    onUpdate("enemy", (enemy) => {
        enemy.move(-400, 0);
    });
    
    // move up 100 pixels per second every frame when "w" key is held down
    onKeyDown("w", () => {
        player.move(0, 100);
    });
  2. Install KAPLAY

    master

    You can get started quickly using the create-kaplay scaffolding tool, or install the package directly via a package manager. Note that you will need a bundler like Vite or ESBuild to use KAPLAY in a local development environment.

    # The fastest way to get started
    npx create-kaplay my-game
    
    # Install with package manager
    npm install kaplay
    yarn add kaplay
    pnpm add kaplay
    bun add kaplay
  3. Quick start with KAPLAY

    master

    To start a game, call kaplay() with an optional configuration object. You can then load assets like sprites using loadSprite() and add game objects to the scene using add(). Game objects are composed of components (like rect(), pos(), area(), body(), or health()), tags for grouping, and plain objects for custom data.

    // Start a game
    kaplay({
        background: "#6d80fa",
    });
    
    // Load an image
    loadSprite("bean", "https://play.kaplayjs.com/bean.png");
    
    // Add a sprite to the scene
    add([
        sprite("bean"), // it renders as a sprite
    ]);
    
    // Add a Game Obj to the scene from a list of components
    const player = add([
        rect(40, 40), // it renders as a rectangle
        pos(100, 200), // it has a position (coordinates)
        area(), // it has a collider
        body(), // it is a physical body which will respond to physics
        health(8), // it has 8 health points
        // Give it tags for easier group behaviors
        "friendly",
        // Give plain objects fields for associated data
        {
            dir: vec2(-1, 0),
            dead: false,
            speed: 240,
        },
    ]);
  4. Configure TypeScript global types

    master

    If you want to use KAPLAY's functions (like vec2()) as globals in a TypeScript project, you have two options:

    Option 1: Import the global directive

    Add this to your entry file:

    import "kaplay/global";

    Add the declaration file to your compilerOptions.types to avoid polluting the global namespace in published games:

    {
      "compilerOptions": {
        "types": ["./node_modules/kaplay/dist/declaration/global.d.ts"]
      }
    }

    Using explicit imports

    Alternatively, you can import types directly to maintain strict typing without globals:

    import type { TextCompOpt } from "kaplay"
    import type * as KA from "kaplay"
    
    interface MyTextCompOpt extends KA.TextCompOpt {
      fallback: string;
    }
  5. Configure 9-slice sprites

    master

    KAPLAY supports 9-slice scaling for sprites via the slice9 configuration in your sprite data. When a sprite is configured with slice9, the tiled option in the sprite() component is ignored in favor of the tileMode defined in the slice9 config.

    Supported tileMode values (within the slice9 definition) typically include:

    • center: Tiles the center area.
    • edges: Tiles the edge areas.
    • all: Tiles all non-corner areas.
  6. Configure the maximum number of debug logs

    master

    The number of messages kept in the on-screen debug log is controlled by the logMax option in your KAPLAYOpt configuration. If logMax is not provided, it defaults to a system constant LOG_MAX.

    This limit ensures that the debug log does not consume excessive memory by continuously unshifting new messages into the game's log array.

  7. Configure particle properties with ParticlesOpt

    master

    The ParticlesOpt object defines the visual and physical characteristics of the particles in the system. Properties can be single values or ranges (provided as [min, max] arrays) to introduce variety.

    Properties:

    • max: (number) Maximum number of simultaneously rendered particles.
    • lifeTime: [number, number] Min/max lifetime in seconds.
    • speed: [number, number] Min/max speed in pixels per second.
    • acceleration: [Vec2, Vec2] Min/max acceleration vector.
    • damping: [number, number] Min/max damping (velocity reduction).
    • angle: [number, number] Min/max start angle.
    • angularVelocity: [number, number] Min/max angular velocity.
    • scales: number[] | Vec2[] Array of scales to interpolate through over the particle's life.
    • colors: Color[] Array of colors to interpolate through over the particle's life.
    • opacities: number[] Array of opacity values (0-1) to interpolate through.
    • quads: Quad[] Array of UV quads to interpolate through.
    • texture: Texture The texture used for all particles.
  8. Define sprite animations with `SpriteAnim`

    master

    Animations are defined within the anims property of LoadSpriteOpt. A SpriteAnim can be a simple number (representing a single frame) or an object defining a sequence.

    Animation Object Properties:

    • from: The starting frame index.
    • to: The end frame index.
    • loop: Whether the animation should loop (boolean).
    • pingpong: If true, the animation moves back to the start instead of jumping to the first frame when looping.
    • speed: Animation speed in frames per second.
    • frames: A specific list of frame indices. Note: If frames is provided, from, to, and pingpong are ignored.
  9. Configure the animate component options

    master

    When calling animate({ ... }) to add the component to a game object, you can provide AnimateCompOpt to set global behaviors for all animations on that object.

    OptionTypeDescription
    followMotionbooleanIf true, animating pos will automatically update the angle to follow the motion. Requires the rotate component.
    relativebooleanIf true, animations are applied relative to the object's base pos, angle, scale, and opacity instead of overriding them.
  10. Configure animation channel options

    master

    When calling obj.animate(name, keys, opts), the opts object (AnimateOpt) defines how that specific property channel behaves.

    OptionTypeDescription
    durationnumberDuration of the animation in seconds.
    loopsnumberNumber of times to loop. undefined or 0 results in infinite looping.
    directionTimeDirectionPlayback behavior: "forward", "reverse", or "ping-pong".
    easingEaseFuncThe easing function applied to the entire animation.
    interpolationInterpolationHow to interpolate between keys: "none", "linear", "slerp", or "spline".
    timingnumber[]Optional array of timestamps (in percent, 0-1) for the keys. If omitted, keys are equally spaced.
    easingsEaseFunc[]Optional array of easing functions for each key interval.
  11. Use 9-slice scaling with `NineSlice`

    master

    The slice9 option allows for proportional scaling of sprites by defining how the image is divided into a 3x3 grid. This is useful for UI elements like buttons or panels.

    Properties:

    • left: Width of the left column.
    • right: Width of the right column.
    • top: Height of the top row.
    • bottom: Height of the bottom row.
    • tileMode: Determines how regions behave when scaled:
      • "none": All regions stretch (default).
      • "edges": Edge regions (top, bottom, left, right) tile, center stretches.
      • "center": Center region tiles, edges stretch.
      • "all": Both edges and center tile. (Corners never tile).