@gaiaengine/2d v0.3.6
@gaiaengine/2d
A TypeScript/ES module built on top of Pixi.js and inspired by @commonmodule/ts. It provides a lightweight 2D game engine framework with:
- Core Node Hierarchy (
GameNode,DisplayNode,TransformableNode, etc.) - Collision Detection (shapes, polygon collision, broad-phase management)
- Resource Loading (textures, spritesheets, audio, text, binary)
- Tile-Based Map Rendering (rectangular grid system, layered terrain and objects)
- UI Components (joystick, DOM overlays, debug displays)
- Sound and Music (background music, sound effects, volume management)
- Scenes and Camera (game scenes, camera movement, zoom, panning)
- Shape Nodes (circles, ellipses, rectangles with optional fill/stroke)
Table of Contents
- Installation
- API Reference
- Usage Examples
- Contributing
- License
Installation
npm install @gaiaengine/2d
# or
yarn add @gaiaengine/2dNote: This library internally depends on Pixi.js (
^7.2.4) and also references @commonmodule/ts for event and resource loading utilities. Make sure these are also installed or available in your environment.
API Reference
Collision
Collidable & Colliders
Collidable: An interface indicating an object has an array of
collidersand aglobalTransformto place them in the game world.export default interface Collidable { colliders: Collider[]; globalTransform: Transform; }Collider: A type union for shape definitions used in collision:
type Collider = | RectCollider | CircleCollider | EllipseCollider | PolygonCollider;Colliders include:
- BaseCollider: minimal
x,yoffset. - RectCollider: rectangle with
width,height. - CircleCollider: circle with
radius. - EllipseCollider: ellipse with
width,height. - PolygonCollider: polygon with a set of
{ x, y }points.
- BaseCollider: minimal
ColliderType: enum to identify shape type:
enum ColliderType { Rectangle, Circle, Ellipse, Polygon, }
CollisionChecker
A static utility class that checks collision between any two colliders of known type. Methods include:
checkCollision(colliderA, transformA, colliderB, transformB)rectRectCollision(...)circleCircleCollision(...)rectCircleCollision(...)polygonPolygonCollision(...)- and many more specialized checks
It also provides point-inside shape checks, line-line intersection checks, and
internal methods to approximate shapes (like approximateCircle,
approximateEllipse) for polygon-based intersection tests.
CollisionDetector & ZoneCollisionDetector
- CollisionDetector: A game node that holds two lists:
subjectsandobstacles. For each frame, it checks collisions between every subject and obstacle and callsonCollision(subject, obstacle)if they overlap. - ZoneCollisionDetector: Extends
CollisionDetectorbut uses aZoneManagerfor broad-phase optimization. Subjects are tested only against obstacles in nearby zones.
Core
GameNode
- A fundamental tree node for building a scene graph.
- It extends
EventTreeNode(from@commonmodule/ts) and maintains a parent-child relationship. append(...)andremove()let you build or tear down node hierarchies.update(deltaTime: number)is called every frame (or on your chosen loop) to update this node and its children.
DisplayNode
- Extends
TransformableNodebut holds a Pixi.jsContainer(or subclass). - Syncs
x,y,scale,rotation, andalphawith the underlying Pixi display object. - Example usage:
class CustomDisplayNode extends DisplayNode { constructor() { super(new Container()); } // ... }
TransformableNode
- A
GameNodewith position, scale, rotation, and alpha. - Maintains both
transform(local) andglobalTransform. - Typically extended by
DisplayNodeorGameObject.
WindowEventNode
- A specialized
GameNodethat can bind window-level events (e.g.keydown,resize) viaonWindow("event", callback). - Automatically unbinds them when removed.
Movable
- A
GameObjectsubclass adding velocity, acceleration, min/max speeds, and optional bounds. move(radian, speed)ormoveTo(x, y, speed, onArrive?)for basic movement logic.stop()to reset speed.
StateSet
- A utility class that handles a set of states (each state is a
GameObject). Only one state is visible at a time. - e.g.,
Idle,Running,Jumpingstates each with their own display object.
Coordinates
A simple interface { x: number; y: number }.
compareCoordinates()
Utility function to check if two coordinates are the same.
Debug Utilities
DebugManager
- Tracks debug statistics, e.g.
displayNodeCount.
DebugDisplay
- A
GameObjectthat shows a small overlay of FPS and current node count. - Appends a text node to the DOM, typically used in dev mode.
DebugColliderDrawNode
- A
GameObjectthat draws the collider shapes (RectCollider,CircleCollider, etc.) as outlines for debugging. - Typically appended to the same parent that has
colliders.
Timers & Delays
Delay
- A
GameNodethat waits a specified duration (delayDuration) before invoking a callback, then removes itself.
Interval
- A
GameNodethat invokes a callback periodically everyintervalDurationseconds, akin tosetInterval, but in the game update loop. - Optionally starts immediately (
startImmediately).
DOM Wrapper
DomWrapperNode
- A subclass of
TransformableNodethat wraps aDomNodefrom @commonmodule/app. - Positions the DOM element in absolute coordinates synchronized with the
engine’s
globalTransformand the current screen scale.
DomTextNode
- A
DomWrapperNodespecialized for text content. this.domNode.text = "...";sets the textual content.
Image & Sprites
BaseImageSprite
- An abstract
GameObjectthat loads and manages a single texture. srcproperty triggers a load.- Subclassed by
SpriteandBackground.
Sprite
- A
BaseImageSpritethat uses either a direct image or a spritesheet frame. - If using a spritesheet +
Atlas, it references a specific frame ID.
AnimatedSprite
- Similar usage to
Sprite, but if you have multiple frames in theatlas.animations, it constructs a PixiAnimatedSprite. - Can set
animation,loop,fps, and handleonAnimationEnd.
Background
- A special
BaseImageSpritethat uses a PixiTilingSprite. - Allows setting
scrollSpeedX,scrollSpeedYfor parallax or scrolling backgrounds.
Input
Joystick & CrossPlatformJoystick
- Joystick: A simple arrow-key-based or WASD-like input class that triggers
onMove(radian)oronRelease(). Also tracks pressed keys. - CrossPlatformJoystick: Extends
Joystick, adding mobile touch-based controls with an on-screen joystickDomNode.- It draws a background “joystick ring” and a “knob”.
- Fires the same callbacks as
Joystickbut uses touch events.
Loading Resources
TextureLoader
- Extends
ResourceLoader<Texture>from@commonmodule/ts. - Loads images into Pixi
Textureobjects. - Uses reference counting and frees them when no longer in use.
SpritesheetLoader
- Extends
ResourceLoader<Spritesheet>. - Given an ID, source URL, and a JSON
Atlas, it loads the image and creates a PixiSpritesheet.
AudioBufferLoader
- Extends
ResourceLoader<AudioBuffer>. - Fetches audio data, decodes it via
AudioContext.decodeAudioData.
BinaryLoader
- Extends
ResourceLoader<Uint8Array>. - Fetches raw binary data from a URL.
TextLoader
- Extends
ResourceLoader<string>. - Fetches text files from a URL.
BitmapFontLoader
- Extends
ResourceLoader<BitmapFont>. - Parses
.fntXML data and related texture. - Produces a
BitmapFontwith character metrics, line height, etc.
ResourcePreloader
- A helper class that can preload a list of resources (text, binary, texture, audio, or spritesheet) in parallel.
Tile Maps
RectMap
- A
RectTileLoadersubclass for rendering a tile map with “rectangular tiles”. - Maintains two layers: terrainLayer and objectLayer.
- Uses a
MapDatastructure to determine which terrain or object ID should be placed at each tile coordinate. - Supports additional “neighbors-based” tiles for corners or transitions.
- Implements deferred loading/unloading of tiles based on camera position (using
tileSizeandextraLoadTileCount).
RectMapObject & RectMapTerrain
- Basic classes that extend
Spriteto represent static, single-frame map sprites, with optional fade-in (fadeDuration).
AnimatedRectMapObject & AnimatedRectMapTerrain
- Extend
AnimatedSprite, allowing multiple-frame animations for map objects or terrains. - Support a fade-in effect too.
MapData
- Defines the structure of the terrain, objects, frames, colliders, etc.
interface MapData { terrains: { [id: string]: TerrainData }; objects: { [id: string]: MapObjectData }; terrainMap: { [cord: string]: string }; mapObjects: { x: number; y: number; object: string }[]; } MapDataTransformercan convertMapDatainto a set of PixiAtlasdata.
TerrainDirection
- An enum describing how to render partial/corner fill for transitions:
- e.g.
TopLeft,FillTopRightBottom, etc.
- e.g.
Particles
ParticleSystem
- A
GameObjectfor creating bursts of particles. - Configurable spawn count, lifetime, direction, speed, fade speed, etc.
- Uses Pixi
Spritefor each particle.
Scenes & Camera
Scene
- An abstract
GameObjectsubclass representing a screen or scene in your game. - Typically manages its own nodes, background, UI, etc.
transitionTo(SomeOtherScene)is an example method that can show aTransitionOverlay.
Camera
- A helper class associated with
GameScreento track camera position (x,y) and scale (zoom). setPosition(x, y), setscale, etc.
TransitionOverlay
- A DOM-based fade overlay that transitions out the current scene and in a new one.
- Typically used by
Scene.transitionTo.
Screens & Layers
GameScreen
- The main rendering surface, built around a Pixi
Rendererwith an internal update loop usingrequestAnimationFrame. - Has a root
SuperRootNode, aCamera, and an optional set of namedLayerobjects. - Accepts options for
width,height,backgroundColor,layers,pixelated.
Fullscreen
- Extends
GameScreen, automatically resizing to fill the browser window. - Attaches to
document.bodyand updates onresizeevents.
LetterboxedScreen
- Extends
GameScreento maintain aspect ratio with letterboxes (black bars). - Uses additional DOM elements to fill in top/bottom/left/right letterbox regions.
PanZoomGameScreen
- Extends
GameScreen, adding “click-and-drag to pan” and “mouse wheel to zoom.” - Saves camera position & zoom in a persistent store.
Layer
- A simple
GameObjectused to group children with a specificzIndex.
SuperRootNode
- A top-level
GameObjectthat sits inside theGameScreen’s renderer. - Usually only used internally; direct parent for layers and the game’s main root node.
Shape Nodes
ShapeNode
- An abstract
DisplayNode<Graphics>that draws a shape on a PixiGraphics. - Subclassed by
CircleNode,EllipseNode,RectangleNode.
CircleNode
- Draws a circle at (0,0) of a given radius.
- Optionally fill or stroke.
EllipseNode
- Draws an ellipse with
width,height.
RectangleNode
- Draws a rectangle with
width,height. - Coordinates are centered by default (
-width/2, -height/2offset).
Audio & Sound
AudioContextManager
- A singleton that holds the
AudioContext. - Checks OGG support, ensures the context is resumed on user interaction.
BackgroundMusic
- Plays a set of looped music tracks (OGG or MP3).
- Randomly chooses among them, restarts on track end, etc.
- Integrates with
VolumeManager.backgroundMusicVolume.
RandomSoundLooper
- Loops random sound effects from a set of sources at a certain volume.
- Pauses/resumes on mobile browser visibility changes.
Sound
- Wraps a single audio buffer playback in the
AudioContext. - Supports play, pause, stop, loop, volume, fade, etc.
- Reference counted by
AudioBufferLoader.
SoundEffectsPlayer
- A singleton that plays short sound effects from a list of URLs, at random, or from a single URL.
- Respects
VolumeManager.soundEffectsVolume.
VolumeManager
- A global volume manager storing two volumes:
backgroundMusicVolumeandsoundEffectsVolume. - Notifies all subscribed sounds or players on changes.
Text & Fonts
BitmapFont
- Represents parsed
.fntdata with a PixiTexture. - Has character metrics and size/lineHeight info.
BitmapTextNode
- A
GameObjectthat lays out text glyphs using a loadedBitmapFont. - Creates a separate Pixi
Spritefor each character, aligned by the font metrics.
TextNode
- A
GameObjectthat renders standard PixiText. - Allows specifying style, anchor, and auto-loading custom fonts via a
FontLoaderfrom@commonmodule/app.
Zoning & Broad-Phase
ZoneManager
- A
GameNodethat divides space into grid “zones”. - For each frame, checks if objects have moved to a new zone and updates them accordingly.
- Ideal for broad-phase collision checks, used by
ZoneCollisionDetector.
Configuration
GaiaEngineConfig
- A simple config singleton with
isDevModeflag. - If
isDevModeistrue, certain debug behaviors are enabled (likeDebugDisplayor console logs).
Usage Examples
1. Creating a Simple GameScreen
import { Fullscreen, GameObject, Sprite } from "@gaiaengine/2d";
const screen = new Fullscreen({ backgroundColor: 0x222222 });
const player = new Sprite(100, 100, "player.png");
screen.root.append(player);
// animate loop is handled by the internal requestAnimationFrame2. Adding Collision Detection
import {
Collidable,
CollisionDetector,
GameObject,
RectCollider,
} from "@gaiaengine/2d";
class Player extends GameObject implements Collidable {
colliders = [
{ type: 0, width: 50, height: 50, x: 0, y: 0 }, // ColliderType.Rectangle=0
];
// ...
}
class Obstacle extends GameObject implements Collidable {
colliders = [
{ type: 0, width: 32, height: 32, x: 0, y: 0 },
];
// ...
}
const detector = new CollisionDetector<Player, Obstacle>(
(subject, obstacle) => {
console.log("Collision detected between", subject, "and", obstacle);
},
);
screen.root.append(detector);
const player = new Player();
const block = new Obstacle();
detector.addSubject(player);
detector.addObstacle(block);3. Using a ParticleSystem
import { ParticleSystem } from "@gaiaengine/2d";
const particles = new ParticleSystem({
src: "star.png",
count: { min: 10, max: 20 },
lifetime: { min: 0.5, max: 1.5 },
direction: { min: 0, max: Math.PI * 2 },
speed: { min: 50, max: 150 },
scale: { min: 0.5, max: 1.0 },
fadingSpeed: -1.0,
rotationToDirection: false,
});
screen.root.append(particles);
particles.burst(200, 200);4. Loading a RectMap
import {
MapData,
RectMap,
ResourcePreloader,
// ...
} from "@gaiaengine/2d";
const mapData: MapData = {
terrains: {/* ... */},
objects: {/* ... */},
terrainMap: {/* "0,0": "grass", etc. */},
mapObjects: [],
};
// Preload required textures/spritesheets
await ResourcePreloader.preloadResources([
{
type: "spritesheet",
id: "my-spritesheet",
src: "atlas.png",
atlas: {/* ... */},
},
]);
// Create a RectMap
const tileMap = new RectMap(
32, // tile size in px
{ mySpritesheet: "atlas.png" }, // map of ID => src
mapData, // the map data
{
extraLoadTileCount: 2,
debounceDelay: 0.2,
tileFadeDuration: 0.5,
},
);
screen.root.append(tileMap);Contributing
- Fork the repository.
- Create a new branch:
git checkout -b feature/my-feature. - Make your changes and commit:
git commit -m "Add my feature". - Push the changes:
git push origin feature/my-feature. - Open a pull request.
License
This package is released under the MIT License. See LICENSE for details.
Author: yj.gaia\ Inspired by: @commonmodule/app\ Pixi.js: https://pixijs.com/
8 months ago
8 months ago
8 months ago
8 months ago
7 months ago
11 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago