Excalibur.js Documentation

repository·main·Indexed 25 days ago

https://github.com/excaliburjs/excalibur

Excalibur.js is a free, open-source 2D game engine written in TypeScript for creating HTML5 canvas games. It simplifies web game development by handling boilerplate engine code and providing cross-platform targeting. The engine includes features such as a rigid-body physics system, Z-indexing for actor layering, support for the HTML5 Gamepad API, and generic lerping and easing functions.

Tokens
149.8K
Snippets
407
Records
684
Agent score
80%

What's inside Excalibur.js

  1. Overview of Excalibur.js

    main

    Excalibur is a free, open-source 2D game engine written in TypeScript for creating HTML5 canvas games. It handles boilerplate engine code and provides cross-platform targeting. It is licensed under the 2-clause BSD license, making it suitable for commercial projects.

    Key resources:

  2. Use the Graph module for connected data

    main

    The Graph module provides a data structure for managing nodes and edges. It supports directed and undirected edges, weighted edges, and spatial positioning for nodes. You can use it to perform graph traversals (BFS, DFS) and pathfinding (Dijkstra, A*).

    import { Graph } from 'excalibur';
    
    // Create an empty graph of strings
    const graph = new Graph<string>();
  3. Core features and capabilities of Excalibur

    main

    Excalibur is an object-oriented, TypeScript-first 2D game engine designed for approachability. It uses a theater metaphor for its API, organizing game logic around Scenes, Actors, and Actions.

    Key features include:

    • Physics & Collisions: Built-in support for both Arcade and Realistic physics models.
    • Graphics & Rendering: Support for Sprites, SpriteSheets, Animations, TileMaps (2D and Isometric), custom shaders (materials), post-processing, and render plugins. The engine uses auto-batching for optimized draw performance.
    • Architecture: While providing an object-oriented API, it uses an Entity-Component-System (ECS) under the hood for advanced control.
    • Tooling Support: Integration with popular game development tools including Tiled maps, LDtk levels, Spritefusion levels, Aseprite image files, and JSFXR audio.
  4. What is the ExcaliburGraphicsContext?

    main

    The ExcaliburGraphicsContext is an abstraction over the underlying drawing mechanism used to display images and graphics. While it is recommended to use ex.Graphics objects with Actors or Entities, you can draw directly to the ExcaliburGraphicsContext for custom rendering needs.

    By default, Excalibur uses WebGL. It can fallback to a 2D Canvas implementation if WebGL is unsupported or hardware acceleration is unavailable. Note that certain features like custom renderers and post processors do not work with the Canvas 2D implementation.

  5. How Queries work in the ECS

    main

    In Excalibur's Entity Component System (ECS), Queries are the mechanism used to filter the World for specific subsets of entities.

    There are two primary types of queries:

    1. Component Queries: Filter entities based on the presence of specific component types. These are typically used by Systems to find entities they need to process.
    2. Tag Queries: Filter entities based on string tags. This is a lightweight way to flag entities for logic (like status effects or AI states) without the overhead of a full component.

    Lifecycle: Queries are not static; they update automatically as part of the World update cycle, ensuring that as entities gain or lose components/tags, the query results remain accurate.

  6. Compose graphics using GraphicsGroup

    main

    A GraphicsGroup is a specialized graphic used to compose multiple graphics into a single unit. It draws its members in relation to one another, allowing you to treat a collection of sprites, text, shapes, or animations as a single entity.

    When creating a GraphicsGroup, you provide a list of members. Each member consists of a graphic and an offset (a Vector) defining its position relative to the group's origin.

    const group = new ex.GraphicsGroup({
      useAnchor: false, // position group from the top left
      members: [
        {
          graphic: newSprite,
          offset: ex.vec(0, 0),
        },
        {
          graphic: newSprite,
          offset: ex.vec(50, 0),
        },
        {
          graphic: text,
          offset: ex.vec(100, 20),
        },
      ],
    })
  7. Use React components in MDX

    main

    Because the documentation uses MDX, you can import and use React components directly inside your Markdown content. This allows for highly interactive documentation pages.

    export const Highlight = ({children, color}) => (
      <span
        style={{
          backgroundColor: color,
          borderRadius: '20px',
          color: '#fff',
          padding: '10px',
          cursor: 'pointer',
        }}
        onClick={() => {
          alert(`You clicked the color ${color} with label ${children}`)
        }}>
        {children}
      </span>
    );
    
    This is <Highlight color="#25c2a0">Docusaurus green</Highlight> !
  8. Compose complex behaviors with Parallel Actions and Sequences

    main

    Because both Parallel Actions and ActionSequences are treated as single actions, they can be nested and composed to create complex game automations. You can run multiple sequences in parallel, or run a parallel group within a sequence.

    Example: Running two sequences in parallel:

    actor.actions.parallel([
      actor.actions.runAction(attackSequence),
      actor.actions.runAction(glowSequence)
    ]);

    Example: Repeating parallel actions using repeatForever:

    let prlAction1 = new ex.ParallelActions([
      new ex.MoveBy(player, 150, 0, 110),
      new ex.ScaleTo(player, 2, 2, 1, 1),
    ]);
    
    let prlAction2 = new ex.ParallelActions([
      new ex.MoveBy(player, -150, 0, 110),
      new ex.ScaleTo(player, 1, 1, 1, 1),
    ]);
    
    player.actions.repeatForever((ctx) => {
      ctx.runAction(prlAction1);
      ctx.runAction(prlAction2);
    });
  9. Use ex.Scene as a Composition Root

    main

    Instead of assembling game logic in the main entry point, extend ex.Scene and use its onInitialize() method to act as a 'Composition Root'. This is where you should instantiate and add your actors, tilemaps, and other game components to the scene.

    class MyLevel extends ex.Scene {
    
      onInitialize() {
         const myActor1 = new ex.Actor({...});
         this.add(myActor1);
    
         const map = new ex.TileMap({...});
         this.add(map);
      }
    }
  10. How the Scene lifecycle works

    main

    A Scene follows a specific lifecycle that dictates how it is initialized, updated, and drawn. For complex games, you can extend the Scene class to hook into these stages:

    1. onPreLoad: Used to register resources (like ImageSource) with the scene's loader.
    2. onInitialize: Called once when the scene is created. Use this to set up scene state, add actors, or preload assets via engine.start(loader).
    3. onActivate: Called every time the engine switches to the scene via goToScene. This is useful for logic that depends on the context of entering the scene (e.g., checking the previousScene). You can pass data to a scene during activation using engine.goToScene('key', data).
    4. onDeactivate: Called when the engine exits the scene. Use this for cleanup, saving state, or garbage collection.

    Each scene can be typed with a data interface to provide type safety for the data passed during activation: class MyScene extends Scene<MyDataType>.