Hooks and creators

Creators

What puts something in the game: the game itself, scenes, sprites, text, models, particles, packs and the rest.

32 functionsThe descriptions and examples come from the engine's own documentation, which is in English.

Game

createGame

Puts a game in the page: a canvas inside target, drawn at width × height.

createGame(target: TGameTarget, game_options: TGameOptions) => (scenes: Readonly<Record<string, TSceneFn>>, initialScene?: string) => TGameInstance
Example
const Title: TSceneFn = () => createScene();
const Level: TSceneFn = () => createScene();

const game = createGame('#game', {
    width: 320,
    height: 224,
    background: '#000000',
    scaling: 'integer',
})({ Title, Level }, 'Title');

game.on('error', (error) => console.error(error));
Full entry in the reference

Scenes

createScene

Ends a scene's body, and is what it returns: return createScene().

createScene(children: typeOperator) => TScene
Example
const Menu: TSceneFn = () => createScene();

const Level: TSceneFn = () => {
    const hero = createSprite({ width: 16, height: 16 });
    useUpdate((delta) => {
        hero.transform.x += 30 * delta;
    });
    return createScene();
};

createGame('#app', { width: 320, height: 240 })({ Menu, Level });
Full entry in the reference

Game objects

createMaterial

Makes a material: a shader of your own, and for models the surface it is drawn over.

Example
const Level = () => {
    const texture = useLoadTexture({ src: '/assets/hero.png' });

    const crt = createMaterial({
        fragment: `fn effect(color: vec4<f32>, uv: vec2<f32>) -> vec4<f32> {
            let band = 0.5 + 0.5 * sin(uv.y * mu.lines + mu.time * 6.0);
            return vec4<f32>(color.rgb * band, color.a);
        }`,
        uniforms: { lines: 200 },
    });

    createSprite({ texture, material: crt });

    return createScene();
};
Full entry in the reference

createMesh

Puts a model in the scene: a shape, somewhere, with a surface.

createMesh(options: TMeshOptions) => TMesh
Example
const Level = () => {
    useCamera3d({ projection: 'perspective', transform: { z: 4 } });
    const crate = createMesh({ geometry: useCubeGeometry(), tint: '#c08040' });

    useUpdate((delta) => {
        crate.transform.rotationY += delta;
    });

    return createScene();
};
Full entry in the reference

createMeshInstances

Puts many of one shape in the scene, drawn in one go: a field of grass, a hillside of rocks, a forest.

createMeshInstances(options: TMeshInstancesOptions) => TMeshInstances
Example
const rocks = createMeshInstances({ geometry: useCubeGeometry(), tint: '#8a8f98', capacity: 500 });

for (let i = 0; i < 500; i++) {
    rocks.set(i, {
        x: Math.random() * 40 - 20,
        z: Math.random() * 40 - 20,
        rotationY: Math.random() * Math.PI,
        scale: 0.5 + Math.random(),
    });
}
Full entry in the reference

createModel

Puts a loaded model in the scene.

createModel(options: TModelOptions) => TModel
Example
const Level = () => {
    useCamera3d({ projection: 'perspective', transform: { z: 6 } });
    useDirectionalLight({ intensity: 1 });

    const tower = useLoadModel({ src: '/models/tower.glb' });
    const placed = createModel({ model: tower, transform: { y: -1 } });

    useUpdate((delta) => {
        placed.transform.rotationY += delta * 0.5;
    });

    return createScene();
};
Full entry in the reference

createNineSlice

Puts a picture in the scene that can be any size without deforming: a panel, a button, a dialogue box, a health bar.

createNineSlice(options: TNineSliceOptions) => TNineSlice
Example
export const Menu: TSceneFn = () => {
    useLoadTexture({ src: '/assets/ui/panel.png', key: 'panel' });
    const panel = createNineSlice({
        key: 'panel',
        slice: 8,
        width: 200,
        height: 64,
        transform: { x: 160, y: 120 },
        onClick: () => { panel.width += 16; },
    });

    return createScene();
};
Full entry in the reference

createPack

Places one thing a pack offers: a box, or a scene as one part of the scene that creates it.

createPack(options: TPackOptions) => TGameObject
Example
const Menu: TSceneFn = () => {
    const ui = useLoadPack({ src: '/packs/ui-kit' });
    createPack({ pack: ui, box: 'Button', transform: { x: 160, y: 120 } });
    createPack({ pack: ui, box: 'Button', transform: { x: 160, y: 160 }, props: { label: 'QUIT' } });
    return createScene();
};
Full entry in the reference

createParticles

Puts an emitter in the scene: a place that makes particles, following an effect from a file.

createParticles(options: TParticlesOptions) => TParticles
Example
const Level = () => {
    const fire = useLoadParticles({ src: '/effects/fire.particles' });

    createParticles({ effect: fire, transform: { x: 150, y: 250 } });

    return createScene();
};
Full entry in the reference

createParticles3d

Puts an emitter in a scene in three dimensions, following an effect written for them.

createParticles3d(options: TParticles3dOptions) => TParticles3d
Example
const Campfire = () => {
    const fire = useLoadParticles({ src: '/effects/campfire3d.particles' });

    createParticles3d({ effect: fire, transform: { y: 0.1 } });

    return createScene();
};
Full entry in the reference

createPolygon

Puts a shape in the scene whose corners the game moves: a picture stretched over an outline that can change every frame.

createPolygon(options: TPolygonOptions) => TPolygon
Example
export const Pond: TSceneFn = () => {
    // A blob of twelve corners round a circle, wobbling.
    const corners = Array.from({ length: 12 }, (_, i) => ({ angle: (i / 12) * Math.PI * 2 }));
    const blob = createPolygon({
        points: corners.map(({ angle }) => ({ x: Math.cos(angle) * 24, y: Math.sin(angle) * 24 })),
        tint: '#5bd75b',
        transform: { x: 160, y: 90 },
    });

    useUpdate((_delta, time) => {
        corners.forEach(({ angle }, i) => {
            const r = 24 + Math.sin(time * 4 + angle * 3) * 3;
            blob.points[i].x = Math.cos(angle) * r;
            blob.points[i].y = Math.sin(angle) * r;
        });
    });
    return createScene();
};
Full entry in the reference

createShapes

Puts shapes in the scene, drawn by the graphics card as they are each frame: rectangles, with rounded corners or not, circles, ellipses and slices of them, outlines of any number of corners (hollowed in too, a star or a letter), and lines as wide as asked for.

createShapes(options: TShapesOptions) => TShapes
Example
export const Level: TSceneFn = () => {
    let life = 1;
    let cooldown = 0;
    const hud = createShapes({
        transform: { x: 8, y: 8 },
        shapes: [
            { type: 'rect', x: 0, y: 0, width: 60, height: 6, radius: 2, fill: '#e15554' },
            { type: 'rect', x: 0, y: 0, width: 60, height: 6, radius: 2, stroke: { width: 1, color: '#ffffff', align: 'outside' } },
            { type: 'circle', x: 80, y: 3, radius: 6, start: -Math.PI / 2, end: -Math.PI / 2, fill: '#ffd23f' },
        ],
    });
    const bar = hud.shapes[0] as TShapeRect;
    const pie = hud.shapes[2] as TShapeCircle;

    useUpdate((delta) => {
        cooldown = Math.min(1, cooldown + delta / 3);
        bar.width = 60 * life;
        pie.end = -Math.PI / 2 + cooldown * Math.PI * 2;
    });
    return createScene();
};
Full entry in the reference

createSpriteTexture

Makes a picture and fills it with a component: whatever component draws, and whatever it creates with useSpawn, ends up in the picture instead of on the screen, every frame.

createSpriteTexture(options: TSpriteTextureOptions, component?: (args: TArgs) => unknown, args: TArgs) => TTexture
Example
const Screen = () => {
    const pet = createSprite({ key: 'pet', transform: { x: 40, y: 40 } });
    useUpdate((delta) => {
        pet.transform.x += delta * 10;
    });
};

const Level = () => {
    useCamera3d({ projection: 'perspective', transform: { z: 3 } });
    const screen = createSpriteTexture({ width: 128, height: 128 }, Screen);
    createMesh({ geometry: useCubeGeometry(), texture: screen });
    return createScene();
};
Full entry in the reference

createText

Writes something on screen with a bitmap font: a score, a title, a menu, "PRESS START".

createText(options: TTextOptions) => TText
Example
export const Level: TSceneFn = () => {
    // No font given: the engine's own.
    const score = createText({ text: 'SCORE 0', style: { fontSize: 16 }, transform: { x: 8, y: 8 } });
    // A font of your own, loaded from its two files.
    const font = useLoadBitmapFont({ json: '/fonts/arcade/arcade.json', atlas: '/fonts/arcade/arcade.png' });
    createText({ text: 'HI SCORE', font, transform: { x: 8, y: 28 } });
    // A font an earlier scene loaded with useLoadFont({ src, key: 'title' }), by its key alone.
    createText({ text: 'LEVEL 1', font: 'title', transform: { x: 8, y: 48 } });
    let points = 0;

    useUpdate(() => {
        points += 1;
        score.text = 'SCORE ' + points;
    });

    return createScene();
};
Full entry in the reference

createView

A view of the world in a rectangle of the screen: half of a split screen, a minimap in a corner, a rear-view mirror.

createView(options: TViewOptions, component?: (args: TArgs) => unknown, args: TArgs) => TSprite
Example
const Half = (player: TSprite) => {
    useCamera2d();
    useCameraFollow(player);
};

const Level = () => {
    useWorldOffScreen();
    const p1 = createSprite({ key: 'hero', transform: { x: 40, y: 200 } });
    const p2 = createSprite({ key: 'hero', transform: { x: 120, y: 200 } });
    createView({ x: 0, y: 0, width: 240, height: 270 }, Half, p1);
    createView({ x: 240, y: 0, width: 240, height: 270 }, Half, p2);
    return createScene();
};
Full entry in the reference

Store

createGameStore

Makes a store: data of the game that outlives a scene (lives, coins, options, a pet), with a way to be told when it changes and, optionally, to be saved and loaded.

createGameStore(config: TGameStoreConfig<S, A>) => TGameStore<S, A>
Example
declare const pet: TSprite;
const GREEN = getColor('#40c040');
const RED = getColor('#e04040');

// stores/pet.ts
export const petStore = createGameStore({
    key: 'pet',
    state: { hunger: 70, timesFed: 0 },
    actions: (set) => ({
        feed: () => set((s) => { s.hunger = Math.min(100, s.hunger + 15); s.timesFed++; }),
    }),
    persist: { adapter: localStorageAdapter() },
});

// when the game starts
await petStore.load();

// in a scene
useStore(petStore, (s) => s.hunger > 30, (content) => { pet.tint = content ? GREEN : RED; });
Full entry in the reference

Signals

createGameSignal

Makes a signal: a way for one part of the game to say "this happened" and for any other part to react, without the two knowing about each other.

createGameSignal() => TGameSignal<T>
Example
let score = 0;

// events.ts
export const coinCollected = createGameSignal<number>();

// coin.ts
coinCollected.emit(10);

// hud.ts, inside a scene
useSignal(coinCollected, (points) => { score += points; });
Full entry in the reference

Sprites

createBackdrop

A strip of picture that repeats endlessly across the world and moves with the camera only so much: the far layers of a platformer, clouds, hills, a city skyline, as the 16-bit consoles drew them.

createBackdrop(options: TBackdropOptions) => TSprite
Example
export const Level: TSceneFn = () => {
    useLoadTexture({ src: '/backdrops/clouds.png', key: 'clouds' });
    useLoadTexture({ src: '/backdrops/hills.png', key: 'hills' });
    createBackdrop({ key: 'clouds', parallax: { x: 0.1, y: 0 }, y: 20 });
    createBackdrop({ key: 'hills', parallax: { x: 0.4, y: 0.2 }, y: 120 });
    return createScene();
};
Full entry in the reference

createMode7

A floor seen in perspective that turns and stretches as the camera moves over it, the Mode 7 of the 16-bit consoles: the track of a kart racer, the world map seen from the air, the arena that spins under a boss.

createMode7(options: TMode7Options) => TMode7
Example
export const Race: TSceneFn = () => {
    useLoadTexture({ src: '/maps/track.png', key: 'track' });
    createBackdrop({ key: 'hills', parallax: { x: 0, y: 0 }, y: 40 });
    const floor = createMode7({ key: 'track', horizon: 76, height: 24, x: 512, y: 900 });
    const tree = createSprite({ key: 'tree', anchor: { x: 0.5, y: 1 } });
    const keys = useKeyboard();

    useUpdate((delta) => {
        if (keys.isDown('ArrowLeft')) floor.uniforms.angle -= delta * 2;
        if (keys.isDown('ArrowRight')) floor.uniforms.angle += delta * 2;
        if (keys.isDown('ArrowUp')) {
            floor.uniforms.x += Math.sin(floor.uniforms.angle) * delta * 200;
            floor.uniforms.y -= Math.cos(floor.uniforms.angle) * delta * 200;
        }
        placeOnMode7(floor, tree, 540, 700);
    });

    return createScene();
};
Full entry in the reference

createSprite

Puts a picture in the scene: an image from useLoadTexture, a frame of a sheet, or a plain coloured rectangle when it has neither.

Example
export const Level: TSceneFn = () => {
    const texture = useLoadTexture({ src: '/assets/hero.png' });
    const hero = createSprite({ texture, transform: { x: 160, y: 120 } });
    // No picture: a coloured rectangle, placed by its top-left corner.
    createSprite({ width: 320, height: 16, tint: '#3a2a1a', anchor: { x: 0, y: 0 }, transform: { y: 224 } });

    useUpdate((delta) => {
        hero.transform.rotation += delta;
    });

    return createScene();
};
Full entry in the reference

Tilemaps

createTilemap

Loads a map and draws it: one call per layer, however many cells it has.

createTilemap(options: TTilemapOptions) => TTilemap
Example
export const Level: TSceneFn = () => {
    const map = createTilemap({ src: '/maps/level1.tilemap' });
    const player = createSprite({ key: 'hero', zIndex: 0 });

    useUpdate((delta) => {
        // The ground layer is drawn under the player and the treetops over them, because the
        // file says 'under' and 'over' and the player never mentioned a number at all.
        if (!solidAtPoint(map, player.transform.x + 8, player.transform.y)) {
            player.transform.x += 60 * delta;
        }
    });

    return createScene();
};
Full entry in the reference

Geometry

createGeometry

Makes a shape of your own, corner by corner: a terrain from a height map, a trail, a ramp, a star pushed out into a solid, anything the shape hooks do not make.

createGeometry(data: TGeometryData) => TGeometry
Example
const Level = () => {
    useCamera3d({ projection: 'perspective', transform: { y: 1, z: 4 } });
    useDirectionalLight({ intensity: 1 });

    // A ramp: four corners and two triangles, counter-clockwise from the side that is seen.
    const ramp = createGeometry({
        positions: [-1, 0, 1, 1, 0, 1, 1, 1, -1, -1, 1, -1],
        indices: [0, 1, 2, 0, 2, 3],
        uvs: [0, 1, 1, 1, 1, 0, 0, 0],
    });
    createMesh({ geometry: ramp, tint: '#ff9e3d' });

    return createScene();
};
Full entry in the reference

Pixels

createPixelsnacatamalon/pixels

A new picture to paint on in code, transparent or filled with one colour: what to use instead of a <canvas> whenever a picture has to be generated rather than drawn.

createPixels(width: number, height: number, fill?: TColorOption) => TPixels
Example
const tile = createPixels(16, 16, '#2a6b3a');
fillRect(tile, 0, 15, 16, 1, '#1a4a28');
Full entry in the reference

createPixelTexturenacatamalon/pixels

Turns a picture into a texture a sprite, a model's material or a shader shows like any image loaded from a file.

createPixelTexture(source: TPixels | TLoadedPixels, paint: TPixelPaint, options?: TPixelTextureOptions) => TTexture
Example
const Level = () => {
    // Painted in code.
    const art = createPixels(16, 16, '#1d2b53');
    fillCircle(art, 8, 8, 6, '#ffec27');
    createSprite({ texture: createPixelTexture(art), width: 64, height: 64 });

    // A drawn sprite in another colour, made from the one file.
    const hero = useLoadPixels({ src: '/assets/hero.png' });
    const red = createPixelTexture(hero, (p) => swapColors(p, [['#3a7bff', '#e23d3d']]));
    createSprite({ texture: red, width: 32, height: 32 });
    return createScene();
};
Full entry in the reference

Assets & loading

createSpriteAtlas

Describes a sheet as a grid of frames, so many pictures can live in one image.

createSpriteAtlas(options: TSpriteAtlasOptions) => TSpriteAtlas
Example
const walk = useLoadTexture({ src: '/assets/walk.png', key: 'walk' });
const sheet = createSpriteAtlas({ texture: walk, columns: 6 });

createSprite({ atlas: sheet, frame: 0, transform: { x: 80, y: 120 } });
Full entry in the reference

Physics

createRetroBody2d

A complete retro collider from a partial description: the sibling of createPhysicsBody2d, so every record that reaches a document is complete by construction.

createRetroBody2d(options: { id, name, body, collider } & Partial<Omit<TRetroSurface, 'solidSides'>> & { solidSides }) => TRetroBody2d
Full entry in the reference

Net

createRoomnacatamalon/net

Makes a room: the game's own scenes running with no screen and no sound, deciding what happens, with players coming in over their connections.

createRoom(options: TRoomOptions) => TRoom
Example
import { createScene, type TSceneFn } from 'nacatamalon';
import { createRoom } from 'nacatamalon/net';

// The game's own scene, as its players' pages run it.
const Lobby: TSceneFn = () => createScene();

// What of socket.io's server this uses (`import { Server } from 'socket.io'`).
type Socket = {
    emit(event: string, text: string): void;
    on(event: string, listener: (value: string) => void): void;
    disconnect(): void;
};
declare const io: { on(event: 'connection', listener: (socket: Socket) => void): void };

const room = createRoom({ width: 320, height: 180, scenes: { Lobby }, step: 20, name: 'lobby' });

io.on('connection', (socket) => {
    let hear: (text: string) => void = () => {};
    socket.on('naca', (text) => hear(text));
    room.join({
        send: (text) => socket.emit('naca', text),
        onMessage: (listener) => { hear = listener; },
        onClose: (listener) => socket.on('disconnect', (reason) => listener(reason)),
        close: () => socket.disconnect(),
    });
});
Full entry in the reference

createRoomStorenacatamalon/net

Declares a room store: data of one room (its score, its round, whose turn it is) that the room changes and every player in it sees, a moment later, read only.

createRoomStore(options: TRoomStoreOptions<S>) => TRoomStoreDecl<S>
Example
import { createScene, createText } from 'nacatamalon';
import { createRoomStore, useNet, useRoomStore } from 'nacatamalon/net';

// stores/score.ts
export const score = createRoomStore({ key: 'score', state: { red: 0, blue: 0 } });

// scenes/match.ts
const Match = () => {
    const net = useNet();
    const board = useRoomStore(score);
    const label = createText({ text: '0 - 0' });
    board.watch((s) => `${s.red} - ${s.blue}`, (text) => { label.text = text; });
    if (board.writable) {
        net.onMessage<'red' | 'blue'>('goal', (team) => board.set((s) => { s[team] += 1; }));
    }
    return createScene();
};
Full entry in the reference

createServernacatamalon/net

Makes a server: it takes players' connections, asks admit who gets in, and gives each room asked for a game of its own (createRoom) running the game's scenes, which ends when its last player leaves.

createServer(options: TServerOptions) => TServer
Example
// server.ts, run with `bun server.ts` (or Node: `node server.js`)
import { createScene, type TSceneFn } from 'nacatamalon';
import { createServer } from 'nacatamalon/net';

// The game's own scenes, as its players' pages run them.
const Lobby: TSceneFn = () => createScene();
const Pool: TSceneFn = () => createScene();

const server = createServer({
    width: 320, height: 180,
    scenes: { Lobby, Pool },
    step: 20,
    roomScene: (room) => (room === 'pool' ? 'Pool' : 'Lobby'),
    admit: async ({ token }) => (await accountOf(token))?.name ?? false,
});
server.listen(8080);

declare function accountOf(token: string | null): Promise<{ name: string } | null>;
Full entry in the reference

Headless

createHeadlessGamenacatamalon/headless

Makes a game that runs with no browser and no screen, in Node or Bun: the same scenes, hooks and updates as in a page, moved a frame at a time by whoever holds it.

createHeadlessGame(options: THeadlessGameOptions) => THeadlessGame
Example
import { expect, test } from 'bun:test';
import { writeFileSync } from 'node:fs';
import { createHeadlessGame } from 'nacatamalon/headless';
import { encodePng } from 'nacatamalon/authoring';
import { Level } from '../src/scenes/level';

test('the player walks right', async () => {
    const game = createHeadlessGame({ width: 320, height: 180, scenes: { Level } });
    await game.loaded();
    const start = game.find('Player')!.transform!.x;

    game.press('ArrowRight');
    game.run(60);
    game.release('ArrowRight');

    expect(game.find('Player')!.transform!.x).toBeGreaterThan(start);
    expect(game.drawn().some((p) => p.text === 'SCORE 0')).toBe(true);
    writeFileSync('level.png', encodePng(game.capture({ scale: 4 })));   // to look at it
    game.destroy();
});
Full entry in the reference