Hooks and creators

Hooks

What a scene or an object asks for while it is being built: loading, input, cameras, lights, sound, state and the game loop.

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

Game

useGame

The game itself: its size, its background, whether images are kept crisp, how fast time runs, and whether everything is frozen.

useGame() => TGameHandle
Example
export const Level: TSceneFn = () => {
    const game = useGame();
    const keys = useKeyboard();

    useUpdate(() => {
        // A pause menu: everything stops, everything is still drawn.
        if (keys.justPressed('Escape')) {
            game.isPaused() ? game.resume() : game.pause();
        }
        // Slow motion while the key is held.
        game.setTimeScale(keys.isDown('Shift') ? 0.25 : 1);
    });

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

Scenes

useScene

Returns the controls for the game's scenes: launch, stop, change, restart, pause, resume, isPaused and isRunning.

useScene() => TSceneHandle
Example
export const Intro: TSceneFn = () => {
    const scene = useScene();
    let elapsed = 0;
    useUpdate((dt) => {
        elapsed += dt;
        if (elapsed > 3) scene.change('Level');
    });
    return createScene();
};
Full entry in the reference

Lifecycle

useCleanup

Runs when its owner goes away: the component it is called in when it is destroyed, or the scene when it stops.

useCleanup(cleanup: () => void) => void
Example
const PauseMenu = () => {
    const onKey = (event: KeyboardEvent) => console.log(event.key);
    window.addEventListener('keydown', onKey);

    // Without this, the listener stays alive after the menu is gone and fires behind it.
    useCleanup(() => window.removeEventListener('keydown', onKey));
};
Full entry in the reference

useLateUpdate

Runs your code once per frame, after every useUpdate of the scene has run.

useLateUpdate(callback: (delta: number, time: number) => void) => void
Example
const Player = () => {
    const place = useTransform({ x: 40, y: 112 });
    useUpdate((delta) => {
        place.x += 100 * delta;
    });
};

export const Level: TSceneFn = () => {
    const camera = useCamera2d();
    const player = useSpawn(Player)();

    useLateUpdate(() => {
        // where the player is now, after its own update moved it this frame
        camera.transform.x = player.transform!.x - 128;
    });

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

useReady

Runs your code once, when everything being built with it exists: the whole scene, children and all, before its first frame.

useReady(callback: () => void) => void
Example
// A behaviour on the root of a scene laid out as a document.
registerScript('match', () => {
    const root = useSelf();

    // Here, in the body, the boxes under the root are not built yet.
    useReady(() => {
        const pitcher = findObject(root, 'Pitcher');
        if (pitcher === null) return;
        useUpdate((delta) => {
            pitcher.transform!.x += 10 * delta;
        });
    });
});
Full entry in the reference

useSceneTransitionEnd

Runs your code once, when the transition this scene came in with is over: the screen uncovered and nothing left over it.

useSceneTransitionEnd(callback: () => void) => void
Example
const Level = () => {
    const song = useSong(useLoadSong({ src: '/music/level.song' }));

    // Not in the body: the screen is still covered while the level loads behind it.
    useSceneTransitionEnd(() => song.play());
    return createScene();
};

useScene().change('Level', { transition: fade(0.6) });
Full entry in the reference

useTimer

Runs code later, in game time: once after a while, or again and again.

useTimer() => TTimer
Example
declare const font: TBitmapFont;
declare const spawnEnemy: () => void;

export const Level: TSceneFn = () => {
    const timer = useTimer();
    const banner = createText({ text: 'READY', font, transform: { x: 160, y: 100 } });

    timer.after(1.5, () => { banner.text = 'GO!'; });
    timer.after(2.5, () => { banner.visible = false; });

    // A new enemy every three seconds, for as long as the level runs
    timer.every(3, () => { spawnEnemy(); });

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

useUpdate

Runs your code once per frame, for as long as the scene is on screen.

useUpdate(callback: (delta: number, time: number) => void) => void
Example
export const Level: TSceneFn = () => {
    const hero = createSprite({ key: 'hero', transform: { x: 40, y: 112 } });

    useUpdate((delta) => {
        // 100 pixels per second, whatever the screen does
        hero.transform.x += 100 * delta;
    });

    const coin = createSprite({ key: 'coin', transform: { x: 200, y: 100 } });
    useUpdate((delta, time) => {
        // bobs up and down once a second
        coin.transform.y = 100 + Math.sin(time * Math.PI * 2) * 4;
    });

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

Game objects

useSelf

The thing being built right now, so it can refer to itself later: almost always to end its own life once it has done its job.

useSelf() => TGameObject
Example
const Spark = () => {
    const self = useSelf();
    let left = 0.4;

    useUpdate((delta) => {
        left -= delta;
        if (left <= 0) {
            destroy(self);
        }
    });
};
Full entry in the reference

useSpawn

Prepares a maker for component, so the scene can create as many of them as it likes, whenever it likes: while it is being built, from a frame, from a timer, from a click.

useSpawn(component: (args: TArgs) => TApi, given: string | TSpawnOptions) => (args: TArgs) => TGameObject<TApi>
Example
// An enemy that its level can hurt.
const Bat = ({ x }: { x: number }) => {
    const self = useSelf();
    let life = 3;
    createSprite({ key: 'bat', transform: { x, y: 120 } });
    return {
        hurt: (damage: number) => {
            life -= damage;
            if (life <= 0) destroy(self);
        },
    };
};

export const Cave: TSceneFn = () => {
    const bat = useSpawn(Bat, 'Bat')({ x: 200 });
    const keys = useKeyboard();

    useUpdate(() => {
        if (keys.justPressed('x')) bat.api.hurt(1);
    });

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

useTransform

Gives this object a place of its own, and moves everything inside it.

useTransform(options: TTransformOptions) => TTransform3d
Example
const Turret = (x: number) => {
    const place = useTransform({ x, y: 200 });

    // Both are placed relative to the turret, so turning it turns them together.
    createSprite({ key: 'base', transform: { x: 0, y: 0 } });
    createSprite({ key: 'barrel', transform: { x: 0, y: -12 } });

    useUpdate((delta) => {
        place.rotation += delta;
    });
};
Full entry in the reference

Scripts

useScript

Attaches a behaviour by name to the object being built, and runs it.

useScript(ref: string, props?: TScriptProps, options: TUseScriptOptions) => void
Example
const Guard = () => {
    const texture = useLoadTexture({ src: '/assets/guard.png' });
    createSprite({ texture, transform: { x: 40, y: 112 } });
    useScript('patrol', { speed: 80 });
};
Full entry in the reference

useScriptApi

Reaches the api of another behaviour on the same object: what its function returned, by the name it was registered under, or what one offered with provide under a word of its own.

useScriptApi(name: string, self?: TGameObject) => () => T | null
Example
registerScript('spin', (self) => {
    let running = true;
    useUpdate((delta) => { if (running) self.drawables[0].transform.rotation += delta; });
    return {
        stop: () => { running = false; },
        start: () => { running = true; },
        isRunning: () => running,
    };
});

registerScript('toggle', () => {
    const spin = useScriptApi<{ stop(): void; start(): void; isRunning(): boolean }>('spin');
    const keys = useKeyboard();

    useUpdate(() => {
        if (!keys.justPressed('Space')) return;
        const api = spin();
        if (api === null) return;
        if (api.isRunning()) api.stop(); else api.start();
    });
}, { requires: ['spin'] });
Full entry in the reference

Input

useActions

The game's named actions.

useActions(options: TUseActionsOptions) => TActionsHandle
Example
declare const hero: TSprite;
declare const jump: () => void;
declare let charge: number;

export const Player: TSceneFn = () => {
    const input = useActions();

    useUpdate((delta) => {
        // Four actions, one direction: the keys, the d-pad and the stick all arrive here, and the
        // dead zone is round, so a gentle diagonal stays a diagonal.
        const { x, y } = input.direction('move_left', 'move_right', 'move_up', 'move_down');
        hero.transform.x += x * 120 * delta;
        hero.transform.y += y * 120 * delta;

        if (input.justPressed('jump')) jump();
        // A trigger bound to 'fire' reads how far it is pulled; a key bound to it reads 1.
        charge = input.value('fire');
    });

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

useDirection

Four actions read as one direction: the way to move a character from the input map.

useDirection(negativeX: string, positiveX: string, negativeY: string, positiveY: string, options: TUseActionsOptions & { deadzone }) => () => { x, y }
Example
declare const hero: TSprite;
const SPEED = 120;

const move = useDirection('move_left', 'move_right', 'move_up', 'move_down');
useUpdate((delta) => {
    const { x, y } = move();
    hero.transform.x += x * SPEED * delta;
    hero.transform.y += y * SPEED * delta;
});
Full entry in the reference

useDraggable

Makes a sprite, a text, a nine-slice, a set of shapes or a whole object follow the pointer that drags it: pressed with the main button or a finger, it moves with it, held where it was taken, until it is let go.

useDraggable(target: TBox | TPointerPicture, options: TUseDraggableOptions) => TDraggableHandle
Example
export const Table: TSceneFn = () => {
    const slot = createSprite({ key: 'slot', transform: { x: 240, y: 120 } });
    useTag('slot').add(slot);

    const card = createSprite({ key: 'card', transform: { x: 80, y: 120 } });
    useDraggable(card, {
        dropOn: 'slot',
        snapBack: true,
        onDragStart: () => { card.zIndex = 10; },
        onDragEnd: ({ dropped }) => {
            card.zIndex = 0;
            // Into the slot, right in the middle.
            if (dropped !== null) {
                card.transform.x = slot.transform.x;
                card.transform.y = slot.transform.y;
            }
        },
    });

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

useDropZone

Makes a sprite, a text, a nine-slice, a set of shapes or a whole object a place things can be dragged into: a slot of an inventory, the square of a board, a bin.

useDropZone(target: TBox | TPointerPicture, options: TUseDropZoneOptions) => TDropZoneHandle
Example
export const Table: TSceneFn = () => {
    const card = createSprite({ key: 'card', transform: { x: 80, y: 120 } });
    useTag('card').add(card);
    useDraggable(card, { snapBack: true });

    const slot = createSprite({ key: 'slot', transform: { x: 240, y: 120 } });
    const zone = useDropZone(slot, {
        accepts: 'card',
        onDrop: (dragged) => {
            if (dragged.transform === null) return;
            dragged.transform.x = slot.transform.x;
            dragged.transform.y = slot.transform.y;
        },
    });

    // Dim while a card could go in, bright while one is over it.
    const idle = getColor('#1e2533');
    const can = getColor('#3a4560');
    const over = getColor('#ffcc33');
    useUpdate(() => {
        slot.tint = zone.isOver() ? over : zone.canDrop() ? can : idle;
    });

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

useGamepad

A gamepad, to ask in every frame what the player is holding, has just pressed, or how far a stick is pushed.

useGamepad(target: TGamepadTarget, options: TUseGamepadOptions) => TGamepad
Example
declare const fire: () => void;

export const Level: TSceneFn = () => {
    const pad = useGamepad();
    const keys = useKeyboard();
    const ship = createSprite({ key: 'ship' });

    useUpdate((delta) => {
        const { x, y } = pad.leftStick();
        ship.transform.x += x * 150 * delta;
        ship.transform.y += y * 150 * delta;
        if (pad.justPressed('a') || keys.justPressed('Space')) fire();
    });

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

useInputMap

Remapping: what a game's controls screen is built on.

useInputMap() => TInputMapHandle
Example
declare const jumpRow: TText;

export const Controls: TSceneFn = () => {
    const map = useInputMap();

    // "Press a key or a button for JUMP..."
    listen(jumpRow, { onClick: () => {
        map.capture((binding) => {
            if (binding === null) return;              // they pressed Escape
            if (map.conflicts(binding, 'jump').length > 0) return;
            map.bind('jump', binding, 0);
        });
    } });

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

useKeyboard

The keyboard, to ask in every frame what the player is holding or has just pressed.

useKeyboard() => TKeyboard
Example
declare const Bullet: (x: number) => void;

export const Level: TSceneFn = () => {
    const keys = useKeyboard();
    const ship = createSprite({ key: 'ship', transform: { x: 160, y: 200 } });
    const fire = useSpawn(Bullet);

    useUpdate((delta) => {
        if (keys.isDown('ArrowLeft')) ship.transform.x -= 150 * delta;
        if (keys.isDown('ArrowRight')) ship.transform.x += 150 * delta;
        if (keys.justPressed('Space')) fire(ship.transform.x);
    });

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

usePointer

Listens to the mouse and to touch: presses, releases, movement, and what is under the pointer.

usePointer() => TPointerHandle
Example
export const Board: TSceneFn = () => {
    const pointer = usePointer();
    const red = getColor('#ff5566');

    pointer.onDown((info) => {
        if (info.target !== null) {
            info.target.tint = red;
        }
    });

    // The wheel zooms the camera: towards you is out, away is in.
    const camera = useCamera2d();
    pointer.onWheel(({ deltaY }) => {
        camera.zoom = Math.min(4, Math.max(0.5, camera.zoom * Math.exp(-deltaY * 0.001)));
    });

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

useTouchAction

Makes what is being built an on-screen button for action: while a finger is on it, or on anything inside it, the action is held, and the game reads it like any other press, actions.isDown('jump'), whatever pressed it.

useTouchAction(action: string) => void
Example
declare const jump: () => void;

const Button = ({ x, action }: { x: number; action: string }) => {
    createSprite({ key: 'button', transform: { x, y: 280 } });
    useTouchAction(action);
};

export const Level: TSceneFn = () => {
    const actions = useActions();
    useSpawn(Button)({ x: 400, action: 'jump' });
    useSpawn(Button)({ x: 440, action: 'fire' });

    useUpdate(() => {
        if (actions.justPressed('jump')) jump();
    });

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

Store

useStore

Reacts from a scene when one value of a store changes, and stops by itself when that part of the scene goes away.

useStore(store: TGameStore<S, A>, selector: TStoreSelector<S, T>, handler: TStoreListener<T>, equals?: (a: T, b: T) => boolean) => void
Example
declare const petStore: TGameStore<{ hunger: number }>;
const GREEN = getColor('#40c040');
const RED = getColor('#e04040');

export const Pet: TSceneFn = () => {
    const pet = createSprite({ tint: GREEN, width: 64, height: 64 });
    useStore(petStore, (s) => s.hunger > 30, (content) => {
        pet.tint = content ? GREEN : RED;
    });
    return createScene();
};
Full entry in the reference

useStoreLink

Says that this object uses one of the game's stores.

useStoreLink(key: string) => void
Example
const Pet = () => {
    useStoreLink('pet');
    // ...and now a behaviour on this object can reach it with storeOf(self).
};
Full entry in the reference

State

useData

State that lives with a piece of the scene, as [data, setData].

useData(initial: T) => [TDataRecord<T>, TDataSetter<T>]
Example
declare const counter: TText;

export const Level: TSceneFn = () => {
    const [lives, setLives] = useData(3);

    useWatch(() => {
        counter.text = `LIVES ${lives.value}`;
    }, [lives]);

    usePointer().onDown(() => setLives((n) => n - 1));

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

useStateMachine

A finite state machine that lives with a piece of the scene: a character that is standing, running or jumping, an enemy that patrols, chases and goes back, a door, a boss, a level's phases.

useStateMachine(initial: NoInfer<S>, states: Record<S, TStateDef>, options?: TStateMachineOptions<P>) => TStateMachine<S>
Example
declare const sheet: TSpriteAtlas;

const Hero = ({ x, y }: { x: number; y: number }) => {
    const sprite = createSprite({ atlas: sheet, frame: 0, transform: { x, y } });
    const anim = useSpriteAnimation(sprite, {
        clips: {
            idle: { frames: [0, 1], fps: 4 },
            run: { frames: [2, 3, 4, 5], fps: 12 },
            jump: { frames: [6], fps: 1 },
            hurt: { frames: [7, 8], fps: 12, loop: false },
        },
        play: 'idle',
    });
    const keys = useKeyboard();

    const hero = useStateMachine('idle', {
        idle: {
            onEnter: () => anim.play('idle'),
            onUpdate: () => {
                if (keys.isDown('ArrowRight')) hero.go('run');
                if (keys.justPressed('Space')) hero.go('jump');
            },
        },
        run: {
            onEnter: () => anim.play('run'),
            onUpdate: (delta) => {
                sprite.transform.x += 90 * delta;
                if (!keys.isDown('ArrowRight')) hero.go('idle');
            },
        },
        jump: {
            onEnter: () => anim.play('jump'),
            onUpdate: () => {
                if (hero.time > 0.6) hero.go('idle');
            },
        },
        hurt: {
            onEnter: () => anim.play('hurt'),
            onUpdate: () => {
                if (hero.time > 0.4) hero.go('idle');
            },
        },
    });

    // What the level can ask of it.
    return { hurt: () => hero.go('hurt', { restart: true }) };
};

export const Level: TSceneFn = () => {
    const hero = useSpawn(Hero, 'Hero')({ x: 40, y: 160 });
    usePointer().onDown(() => hero.api.hurt());
    return createScene();
};
Full entry in the reference

useWatch

Runs your code on the first frame, and again whenever one of the things you listed changes.

useWatch(fn: () => void, deps: typeOperator) => void
Example
declare const counter: TText;
declare const hero: TSprite;

declare const coins: TGameStore<{ coins: number }>;

export const Level: TSceneFn = () => {
    const texture = useLoadTexture({ src: '/assets/hero.png' });
    const [lives, setLives] = useData(3);

    useWatch(() => {
        counter.text = `LIVES ${lives.value}  COINS ${coins.state.coins}`;
        hero.visible = texture.status === 'ready';
    }, [lives, coins, texture]);

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

Signals

useReport

Lets a piece report to whoever placed it, and gives back the function that sends the report: a pack's button saying it was pressed, a behaviour saying its box is out of lives.

useReport(name: string) => (payload: T) => boolean
Example
registerScript('button', (self, props) => {
    const pressed = useReport<{ label: string }>('pressed');
    listen(self, { onClick: () => pressed({ label: String(props.label) }) });
});
Full entry in the reference

useSignal

Listens to a signal from a scene, and stops listening by itself when that part of the scene goes away.

useSignal(signal: TGameSignal<T>, handler: TSignalHandler<T>) => void
Example
declare const coinCollected: TGameSignal<number>;

export const Hud: TSceneFn = () => {
    let score = 0;
    useSignal(coinCollected, (points) => { score += points; });
    return createScene();
};
Full entry in the reference

Particles

useParticleCollider2d

Makes this object solid to particles in a flat scene: sparks bounce off it and rain ends on it.

useParticleCollider2d(options: { shape, enabled }) => TParticleCollider2d
Example
const Ledge = () => {
    useTransform({ x: 200, y: 300 });
    useParticleCollider2d({ shape: { kind: 'rect', width: 120, height: 16 } });
};
Full entry in the reference

useParticleCollider3d

Makes this object solid to particles in three dimensions.

useParticleCollider3d(options: { shape, enabled }) => TParticleCollider3d
Example
const Step = (y: number, z: number) => {
    useTransform({ y, z });
    createMesh({ geometry: useCubeGeometry() });
    useParticleCollider3d({ shape: { kind: 'box', size: [1, 1, 1] } });
};
Full entry in the reference

Camera

useCamera2d

Gives the scene a camera, so its world can be bigger than the screen and scroll, turn and zoom.

useCamera2d(options?: TCamera2dOptions) => TCamera2d
Example
export const Level: TSceneFn = () => {
    const camera = useCamera2d();
    const hero = createSprite({ key: 'hero', transform: { x: 900, y: 600 } });

    useUpdate(() => {
        // The screen is 480x320: half of it keeps the hero in the middle
        camera.transform.x = hero.transform.x - 240;
        camera.transform.y = hero.transform.y - 160;
    });

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

useCamera3d

Gives the scene a camera to look at its models through, and returns it.

useCamera3d(options: TCamera3dOptions) => TCamera3d
Example
const Level = () => {
    const camera = useCamera3d({ projection: 'perspective', transform: { z: 6 } });

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

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

useCameraFollow

Makes the scene's camera follow something, the way a platformer's does: a box in the middle the character moves inside freely (deadzone), never past the edges of the level (bounds), a little ahead of where it goes (lead), and a shake for when something hits hard.

useCameraFollow(target: TCameraTarget | null, options: TCameraFollowOptions) => TCameraFollow
Example
declare const Hero: () => void;

export const Level: TSceneFn = () => {
    const map = createTilemap({ src: '/maps/level.tilemap' });
    const hero = useSpawn(Hero)();
    const follow = useCameraFollow(hero, { deadzone: { width: 32, height: 48 }, bounds: map });
    const keys = useKeyboard();

    useUpdate(() => {
        if (keys.justPressed('x')) follow.shake(4, 0.3);
    });
    return createScene();
};
Full entry in the reference

useFog

Puts the scene in fog: its models fade into color between near and far from the camera.

useFog(options: TFogOptions) => TFog
Example
export const Level: TSceneFn = () => {
    useCamera3d({ projection: 'perspective', transform: { z: 8 } });
    const fog = useFog({ color: '#1a1426', near: 6, far: 40 });

    useUpdate((delta, time) => {
        // Breathing: the fog comes in and goes out
        fog.far = 40 + Math.sin(time) * 10;
    });

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

useParallax

Makes this object, and everything it draws and holds, move with the camera only so much: 1 as everything else, 0 not at all, as if pinned to the screen, and in between further away.

useParallax(factor: { x, y }) => void
Example
const Mountains = () => {
    useParallax({ x: 0.3, y: 0 });
    createSprite({ key: 'mountains', transform: { x: 240, y: 120 } });
};
Full entry in the reference

useScreenSpace

Keeps what is created here fixed on the screen, even while the scene's camera moves.

useScreenSpace(on: boolean) => void
Example
const Hud = () => {
    useScreenSpace();
    createSprite({ tint: '#4ade80', width: 120, height: 8, transform: { x: 70, y: 16 } });
};

export const Level: TSceneFn = () => {
    useCamera2d();
    useSpawn(Hud)();
    return createScene();
};
Full entry in the reference

useWorldOffScreen

Has the screen draw only what this scene pins to it (useScreenSpace): its world is seen through views of it alone (createSpriteTexture({ sees: 'world' })).

useWorldOffScreen(on: boolean) => void
Example
declare const Half: (player: TSprite) => void;
declare const Screens: (left: TTexture, right: TTexture) => void;

export const Level: TSceneFn = () => {
    useWorldOffScreen();
    const p1 = createSprite({ key: 'red' });
    const p2 = createSprite({ key: 'blue' });
    const left = createSpriteTexture({ width: 240, height: 270, sees: 'world' }, Half, p1);
    const right = createSpriteTexture({ width: 240, height: 270, sees: 'world' }, Half, p2);
    // The two halves, pinned to the screen in a part of their own.
    useSpawn(Screens)(left, right);
    return createScene();
};
Full entry in the reference

Masks

useMask

Makes a mask: what keeps objects, and everything under them, to a rectangle or to the shape of another object, so nothing of them is drawn, or touched by the pointer, outside it.

useMask(options: TMaskOptions) => TMask
Example
const Flashlight = () => {
    useTransform({ x: 100, y: 80 });
    createSprite({ texture: 'cone' });
};

const Ground = () => {
    createSprite({ texture: 'cave' });
};

const Bats = () => {
    createSprite({ texture: 'bat', transform: { x: 200, y: 60 } });
};

export const Cave: TSceneFn = () => {
    const light = useSpawn(Flashlight)();
    const mask = useMask({ by: light, soft: true });
    mask.add(useSpawn(Ground)());
    mask.add(useSpawn(Bats)());
    useTween()({ from: 40, to: 300, duration: 2, yoyo: true, loop: true, onUpdate: (x) => { light.transform!.x = x; } }).play();
    return createScene();
};

const Inventory = () => {
    useMask({ rect: { x: 0, y: 0, width: 200, height: 120 } }).add(useSelf());
    createSprite({ texture: 'items' });
};
Full entry in the reference

Filters

useFilternacatamalon/effects

Makes a filter: effects run over what an object, and everything under it, draws, before it is laid on the screen.

useFilter(options: TFilterOptions) => TFilter
Example
const Hero = () => {
    createSprite({ texture: 'body' });
    createSprite({ texture: 'sword', transform: { x: 10, y: -4 } });
};

export const Level: TSceneFn = () => {
    const hero = useSpawn(Hero)();
    useFilter({ effects: [outline({ color: '#ffffff' }), dropShadow({ offset: { x: 2, y: 3 } })] }).add(hero);

    const coin = useSpawn(() => { createSprite({ texture: 'coin' }); })();
    const shine = useFilter({ effects: [glow({ color: '#ffd23f' })] });
    shine.add(coin);
    let time = 0;
    useUpdate((delta) => {
        time += delta;
        shine.effects[0]!.uniforms.intensity = 1.5 + Math.sin(time * 4) * 0.5;
    });

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

Lighting

useAmbientLight

The level everything is lit to before any lamp reaches it.

useAmbientLight(options: { color, intensity, ground }) => TAmbientLight
Example
const Level = () => {
    useCamera3d({ projection: 'perspective', transform: { z: 5 } });
    useAmbientLight({ intensity: 1.2 });
    // Or two colours, a sky above and a floor below:
    // useAmbientLight({ color: '#dce6ff', ground: '#4a3328', intensity: 0.5 });
    createMesh({ geometry: useSphereGeometry() });

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

useBlobShadow

Puts a soft dark disc on the ground under something and keeps it there.

useBlobShadow(options: TBlobShadowOptions) => TMesh
Example
const Level = () => {
    useCamera3d({ projection: 'perspective', transform: { y: 3, z: 6, rotationX: -0.5 } });
    createMesh({ geometry: usePlaneGeometry({ width: 12, depth: 12 }) });

    const hero = createMesh({ geometry: useCubeGeometry(), transform: { y: 0.5 } });
    useBlobShadow({ target: hero, radius: 0.75, followHeight: true });

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

useLight2d

A lamp for a 2D world: it lights the sprites, texts, nine-slices, maps and particles around it, with no normal map.

useLight2d(options: TLight2dOptions) => TLight2d
Example
useAmbientLight2d({ intensity: 0.15 });
useLight2d({ transform: { x: 160, y: 90 }, radius: 100, color: '#ffbb66' });
Full entry in the reference

usePointLight

A lamp: it has a place, shines every way, and fades out with distance.

usePointLight(options: TLightOptionsBase & { range }) => TPointLight
Example
const Level = () => {
    useCamera3d({ projection: 'perspective', transform: { z: 5 } });
    usePointLight({ intensity: 1.2 });
    createMesh({ geometry: useSphereGeometry() });

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

useRectLight

A panel: a lamp shaped like a rectangle, which shines from its front only.

useRectLight(options: TLightOptionsBase & { range, width, height }) => TRectLight
Example
const Room = () => {
    useCamera3d({ projection: 'perspective', transform: { y: 2, z: 6 } });
    useRectLight({ width: 3, height: 0.4, range: 6, transform: { y: 3 } });
    createMesh({ geometry: usePlaneGeometry({ width: 10, depth: 10, widthSegments: 20, depthSegments: 20 }) });

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

useSpotLight

A torch: a lamp that only shines inside a cone.

useSpotLight(options: TLightOptionsBase & { range, angle, penumbra }) => TSpotLight
Example
const Level = () => {
    useCamera3d({ projection: 'perspective', transform: { z: 5 } });
    useSpotLight({ intensity: 1.2 });
    createMesh({ geometry: useSphereGeometry() });

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

useStudio

Lights the scene like a photographer's studio in one line, the lighting of the glossy product shots and toys of the era's computer graphics: a warm key light up to the right that casts the shadows, a cool panel filling from the left, a panel behind that draws a bright rim, and the light from all around in two colours, a sky above and a floor below.

useStudio(options: TStudioOptions) => TStudio
Example
const Showroom = () => {
    useCamera3d({ projection: 'perspective', fov: 40, transform: { y: 1.2, z: 6 } });
    useRenderStyle(RENDER.STYLES.cgi);
    const studio = useStudio({ ground: '#3a2a22' });

    createMesh({ geometry: useSphereGeometry(), material: createMaterial(chrome({ environment: studio.environment })) });
    studio.fill.intensity = 0.4;

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

useUnlit2d

Leaves what is created here out of the scene's 2D lights: it keeps its own colours however dark the world is, and still moves with the camera, unlike the HUD.

useUnlit2d(on: boolean) => void
Example
const Torch = () => {
    useLight2d({ radius: 90, color: '#ff9c3a' });
    useSpawn(() => {
        useUnlit2d();
        createSprite({ width: 6, height: 6, tint: '#ffcf6b' });
    })();
};
Full entry in the reference

Geometry

useCubeGeometry

A cube, or any box shape: as wide, tall and deep as you ask, its edges sharp or cut off with a bevel: rounded, or a straight cut.

useCubeGeometry(options: TCubeGeometryOptions) => TGeometry
Example
const Level = () => {
    useCamera3d({ projection: 'perspective', transform: { z: 4 } });
    const shape = useCubeGeometry();
    createMesh({ geometry: shape });

    // A button with its edges rounded off.
    const button = useCubeGeometry({ width: 1, height: 0.3, depth: 1, bevel: { size: 0.1 } });
    createMesh({ geometry: button, transform: { x: 1.5 } });

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

useExtrudeGeometry

A flat outline pushed out into a solid, as a cookie cutter goes through dough: a diamond, a star, a letter, a gear, a notched separator, a deflector, a frame with its window cut out.

useExtrudeGeometry(options: TExtrudeGeometryOptions) => TGeometry
Example
const Level = () => {
    useCamera3d({ projection: 'perspective', transform: { z: 3 } });
    useDirectionalLight({ intensity: 1 });

    // A diamond with its edges rounded off.
    const diamond = useExtrudeGeometry({
        outline: [{ x: 0, y: 0.5 }, { x: 0.3, y: 0 }, { x: 0, y: -0.5 }, { x: -0.3, y: 0 }],
        depth: 0.1,
        bevel: { size: 0.02, segments: 2 },
    });
    createMesh({ geometry: diamond, tint: '#e8c547' });

    // A frame: a square with a square window.
    const frame = useExtrudeGeometry({
        outline: [{ x: -1, y: -1 }, { x: 1, y: -1 }, { x: 1, y: 1 }, { x: -1, y: 1 }],
        holes: [[{ x: -0.7, y: -0.7 }, { x: 0.7, y: -0.7 }, { x: 0.7, y: 0.7 }, { x: -0.7, y: 0.7 }]],
        depth: 0.2,
    });
    createMesh({ geometry: frame, tint: '#8a5a33', transform: { x: 2 } });

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

useLatheGeometry

A shape turned on a lathe: half an outline, its profile, spun about the upright axis into a solid, as a turner shapes a chair leg or a potter a vase.

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

    const bottle = useLatheGeometry({
        profile: [
            { x: 0, y: 0 },       // the middle of the base
            { x: 0.4, y: 0 },     // its rim, given twice: a hard edge
            { x: 0.4, y: 0 },
            { x: 0.4, y: 1.2 },   // the body
            { x: 0.15, y: 1.6 },  // the shoulder
            { x: 0.12, y: 2 },    // the neck, open at the top
        ],
        segments: 24,
    });
    createMesh({ geometry: bottle, tint: '#5fd068' });

    // A wheel of 37 pockets, red and black and one green, as one shape.
    const pocket = useLatheGeometry({
        profile: [{ x: 1.3, y: 0 }, { x: 1, y: 0 }],
        arc: (Math.PI * 2) / 37,
        segments: 1,
    });
    const wheel = mergeGeometries(Array.from({ length: 37 }, (_, i) => ({
        geometry: pocket,
        rotationY: (i * Math.PI * 2) / 37,
        tint: i === 0 ? '#1f8a3b' : i % 2 === 1 ? '#c0282d' : '#1b1b1b',
    })));
    createMesh({ geometry: wheel, transform: { x: 2 } });

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

Animation

useMotion

Plays a motion on the scene this is called in: a .motion file of values moved over time by keys (a camera sweeping the field, a title coming in), made in an editor's motion panel.

useMotion(motion: TMotionDoc | TMotionFile, options: TMotionOptions) => TMotionHandle
Example
export const Intro: TSceneFn = () => {
    const intro = useMotion(useLoadMotion({ src: '/motions/intro.motion' }), { autoplay: true });
    intro.on('titleShown', () => console.log('the title is up'));
    intro.onEnd(() => console.log('over'));
    return createScene();
};
Full entry in the reference

useSkeletalAnimation

Makes a placed model move: plays the movements its file came with, and eases between them.

useSkeletalAnimation(model: TAnimatable, options: TSkeletalAnimationOptions) => TSkeletalAnimation
Example
export const Level: TSceneFn = () => {
    useCamera3d({ projection: 'perspective', transform: { z: 200 } });
    useDirectionalLight({ intensity: 1 });

    const file = useLoadModel({ src: '/models/fox.glb' });
    const fox = createModel({ model: file });
    const moves = useSkeletalAnimation(fox, { play: 'Walk', fade: 0.25 });

    const keys = useKeyboard();
    useUpdate(() => {
        if (keys.justPressed('Space')) moves.play('Run');
    });

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

useSpriteAnimation

Plays a sprite's pictures in order, so it walks, attacks or spins.

useSpriteAnimation(sprite: TSprite, options: TSpriteAnimationOptions) => TSpriteAnimation
Example
declare const walk: TSpriteAtlas;
declare let hurt: boolean;

const enemy = createSprite({ atlas: walk, frame: 0, transform: { x: 80, y: 120 } });

const anim = useSpriteAnimation(enemy, {
    clips: {
        walk: { frames: [0, 1, 2, 3, 4, 5], fps: 12 },
        hit: { frames: [6, 7], fps: 20, loop: false },
    },
    play: 'walk',
});

useUpdate(() => {
    if (hurt) anim.play('hit');
});
Full entry in the reference

useTween

Declares tweens: a number, or the fields of an object, going from one value to another over time, so something can slide in, grow, fade or bounce without you writing the arithmetic for it every frame.

useTween() => TTweenStarter
Example
export const Level: TSceneFn = () => {
    const hero = createSprite({ key: 'hero', transform: { x: 40, y: 112 } });
    const door = createSprite({ key: 'door', transform: { x: 280, y: 112 } });
    const coin = createSprite({ key: 'coin', transform: { x: 160, y: 90 } });
    const tween = useTween();

    // Up and down for ever, from the moment the scene starts
    tween({ target: coin, to: { transform: { y: 84 } }, duration: 0.6, ease: easeInOutSine, yoyo: true, loop: true }).play();

    // Declared once, played on every hit: two blinks and a step back at the same time
    const hurt = tween.all(
        tween({ target: hero, to: { tint: { a: 0 } }, duration: 0.08, yoyo: true, repeat: 3 }),
        tween({ target: hero, by: { transform: { x: -12 } }, duration: 0.2, ease: easeOutQuad }),
    );
    const keys = useKeyboard();
    useUpdate(() => {
        if (keys.justPressed('h')) hurt.play();
    });

    // One after another: the door opens, then the hero walks through
    tween.chain(
        tween({ target: door, to: { transform: { y: -40 } }, duration: 0.5 }),
        tween({ target: hero, to: { transform: { x: 300 } }, duration: 1 }),
    ).play();

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

Materials

useEnvironment

The surroundings of a place, captured: the scene drawn round it as the six faces of a cube, for a model of chrome to reflect the room it is really in, the columns and the torches and the floor, rather than a picture of somewhere else.

useEnvironment(options: TEnvironmentOptions) => TEnvironment
Example
import { chrome, createMaterial, createModel, useEnvironment, useLoadModel } from 'nacatamalon';

const hero = createModel({ model: useLoadModel({ src: '/models/hero.glb' }) });
const room = useEnvironment({ around: hero, height: 1, live: true });
for (const part of hero.parts) part.material = createMaterial(chrome({ environment: room }));
Full entry in the reference

useMirror

A mirror: the world reflected in a flat surface, a polished floor, a mirror on a wall, a lake.

useMirror(options: TMirrorOptions) => TMirror
Example
import { createMesh, useMirror, usePlaneGeometry } from 'nacatamalon';

// A polished floor, softened a little.
createMesh({
    geometry: usePlaneGeometry({ width: 20, depth: 20 }),
    tint: '#2a2622',
    perPixel: true,
    reflection: useMirror({ front: 0.25, blur: 2 }),
});
// A mirror on a wall: the plane stood up, facing the room.
createMesh({
    geometry: usePlaneGeometry({ width: 2, depth: 3 }),
    transform: { z: -5, y: 1.5, rotationX: Math.PI / 2 },
    reflection: useMirror({ front: 0.9 }),
});
Full entry in the reference

Post-processing

useOverlay

Draws what is created here over the screen effects (usePostProcess, a project's post, a style's), untouched by them: a HUD that a bloom does not make glow, a menu that the blur behind it does not blur.

useOverlay(on: boolean) => void
Example
const Level = () => {
    // Started once the level is up, so the HUD goes over it.
    const scenes = useScene();
    useReady(() => scenes.launch('Hud'));
    return createScene();
};

const Hud = () => {
    useScreenSpace();
    useOverlay();
    createText({ text: 'POINTING AT 17', transform: { x: 8, y: 8 } });
    return createScene();
};

// The world, its bloom, the HUD, then a CRT over all of it.
createGame('#app', { post: [{ builtin: 'bloom' }, { overlay: true }, { builtin: 'crt' }] })({ Level, Hud });
Full entry in the reference

usePostProcessnacatamalon/effects

Adds a full-screen effect: a shader that reads the finished frame and gives back what to show.

usePostProcess(options: TPostProcessOptions<U>) => TPostEffect<U>
Example
const Level = () => {
    const nes = useLoadPalette({ src: '/palettes/nes.palette' });

    usePostProcess({ ...paletteMatch(), palette: nes });

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

Color & palettes

Pixels

useLoadPixelsnacatamalon/pixels

Loads a drawn picture as pixels, to process it in code: a palette swap, a white silhouette for a hit, an outline, a collision mask taken from the drawing, a level read from an image.

useLoadPixels(options: TUseLoadPixelsOptions) => TLoadedPixels
Example
const Level = () => {
    const hero = useLoadPixels({ src: '/assets/hero.png' });
    const gold = createPixelTexture(hero, (p) => swapColors(p, [['#3a7bff', '#ffd75a']]));
    createSprite({ texture: gold, width: 32, height: 32 });
    return createScene();
};
Full entry in the reference

Audio

useAudio

The game's volumes: the general one and one per channel, plus a way to silence everything.

useAudio() => TAudioHandle
Example
declare const settings: TGameStore<{ music: number }>;
declare const quieter: TText;

export const Options: TSceneFn = () => {
    const audio = useAudio();
    audio.setVolume(settings.state.music, 'music');

    listen(quieter, { onClick: () => audio.setVolume(audio.getVolume('music') - 0.1, 'music') });
    return createScene();
};
Full entry in the reference

useAudioListener

Puts the game's ears on this object: every sound placed in the world is heard from where it is, and in a 3D scene, facing the way it faces.

useAudioListener(options: { enabled }) => TAudioListener
Example
const Player = () => {
    useTransform({ x: 0, y: 0.5, z: 0 });
    createMesh({ geometry: useCubeGeometry() });
    useAudioListener();
};
Full entry in the reference

useMusic

Plays one piece of music recorded in several files (its layers, or stems) that sound together, and hands back the controls for it.

useMusic(options: TMusicOptions) => TMusicHandle
Example
declare const player: TSprite;

const Level = () => {
    const music = useMusic({
        layers: {
            land: { src: '/audio/theme_land.ogg' },
            water: { src: '/audio/theme_water.ogg', volume: 0 },
        },
        autoplay: true,
    });

    useUpdate(() => {
        const under = player.transform.y < 0;
        music.setLayer('land', under ? 0 : 1, 0.5);
        music.setLayer('water', under ? 1 : 0, 0.5);
    });
    return createScene();
};
Full entry in the reference

useSong

Plays a song written as notes (a .song file, or one written in code) with the engine's 8-bit synthesizer, and hands back the controls.

useSong(song: TSongDoc | TSongFile | TSongAccompaniment, options: TSongOptions) => TSongHandle
Example
declare const crowd: TSprite;
declare const lastInning: TGameSignal;

const Ballpark = () => {
    const song = useSong(useLoadSong({ src: '/music/minuet.song' }), { autoplay: true });

    song.onBeat((beat) => {
        crowd.transform.y = beat === 1 ? 118 : 120;
    });
    useSignal(lastInning, () => song.setTempo(song.tempo * 1.2));
    return createScene();
};
Full entry in the reference

useSound

Plays one audio file (.wav, .mp3, .ogg), or an effect made from a preset, and hands back the controls for it.

useSound(source: TSoundSource, options: TSoundOptions) => TSoundHandle
Example
export const Level: TSceneFn = () => {
    const music = useSound({ src: '/audio/theme.mp3' }, { channel: 'music', loop: true, autoplay: true });
    const jump = useSound({ src: '/audio/jump.mp3' }, { volume: 0.6 });
    const keys = useKeyboard();

    useUpdate(() => {
        if (keys.justPressed('Space')) jump.play();
    });

    useScene().onPaused(() => music.setVolume(0.2));
    return createScene();
};
Full entry in the reference

Assets & loading

useLoadAtlas

Loads a sheet written as a file: the image, how it is cut into frames, and the named runs of frames over it.

useLoadAtlas(options: TUseLoadAtlasOptions) => TLoadedAtlas
Example
export const Level: TSceneFn = () => {
    const coin = useLoadAtlas({ src: '/assets/atlases/coin.atlas' });

    const sprite = createSprite({ atlas: coin, transform: { x: 160, y: 120 } });
    // The runs come from the file, so the clip is not written twice.
    useSpriteAnimation(sprite, { clips: coin.sequences, play: 'spin' });

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

useLoadAudio

Loads a sound, and hands it back at once, still loading, for useSound to play.

useLoadAudio(options: TUseLoadAudioOptions) => TAudioClip
Example
declare const chest: TSprite;

export const Level: TSceneFn = () => {
    const coin = useLoadAudio({ src: '/audio/coin.mp3', key: 'coin' });
    const pickup = useSound(coin);
    listen(chest, { onClick: () => pickup.play() });
    return createScene();
};
Full entry in the reference

useLoadBitmapFont

Loads a bitmap font: an image with the characters drawn in it, and a file saying where each one is.

useLoadBitmapFont(options: TUseLoadBitmapFontOptions) => TBitmapFont
Example
export const Title: TSceneFn = () => {
    const font = useLoadBitmapFont({
        json: '/fonts/arcade/arcade.json',
        atlas: '/fonts/arcade/arcade.png',
    });

    createText({ text: 'PRESS START', font, transform: { x: 16, y: 16 } });

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

useLoadFont

Loads a vector font: a .ttf or .woff file, the kind a computer has installed.

useLoadFont(options: TUseLoadFontOptions) => TFont
Example
export const Title: TSceneFn = () => {
    const font = useLoadFont({ src: '/fonts/Inter.ttf' });

    createText({ text: '¡Hola, ñandú!', font, style: { fontSize: 32 }, transform: { x: 16, y: 16 } });

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

useLoadModel

Loads a model made somewhere else: something sculpted in Blender, bought in a pack, exported from anywhere that writes glTF.

useLoadModel(options: TUseLoadModelOptions) => TGltfModel
Example
export const Level: TSceneFn = () => {
    useCamera3d({ projection: 'perspective', transform: { z: 6 } });
    useDirectionalLight({ intensity: 1 });

    const tower = useLoadModel({ src: '/models/tower.glb' });
    const placed = createModel({ model: tower });

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

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

useLoadPack

Loads a pack: boxes and scenes somebody made in another project, with everything they need.

useLoadPack(options: TUseLoadPackOptions) => TLoadedPack
Example
const Plaza: TSceneFn = () => {
    const signs = useLoadPack({ src: '/packs/signpost' });
    createPack({ pack: signs, box: 'Signpost', transform: { x: 100, y: 120 } });
    return createScene();
};
Full entry in the reference

useLoadProgress

Keeps count of what a scene is loading, for a loading bar or to wait before changing scene.

useLoadProgress(assets?: typeOperator) => TLoadProgress
Example
export const Loading: TSceneFn = () => {
    const scene = useScene();
    const loader = useLoadProgress([
        useLoadTexture({ src: '/assets/hero.png', key: 'hero' }),
        useLoadTexture({ src: '/assets/tiles.png', key: 'tiles' }),
    ]);
    const bar = createSprite({ width: 0, height: 8, transform: { x: 60, y: 112 } });
    useUpdate(() => {
        bar.width = loader.progress * 200;
        if (loader.done) scene.change('Level');
    });
    return createScene();
};
Full entry in the reference

useLoadScene

Loads a scene laid out in the editor: a .scene file.

useLoadScene(options: TUseLoadSceneOptions) => TLoadedScene
Example
const Loading: TSceneFn = () => {
    const scene = useScene();
    const cave = useLoadScene({ src: 'scenes/cave.scene' });
    const loader = useLoadProgress();
    useUpdate(() => {
        if (loader.done) scene.change(cave.name);
    });
    return createScene();
};
Full entry in the reference

useLoadShadernacatamalon/shader

Loads a shader written in a file, so an effect can live beside the game instead of inside it.

useLoadShader(options: TUseLoadShaderOptions) => TShader
Example
export const Level: TSceneFn = () => {
    const crt = useLoadShader({ src: '/shaders/crt.wgsl' });
    const texture = useLoadTexture({ src: '/assets/hero.png' });

    createSprite({ texture, material: createMaterial({ effect: crt, uniforms: { lines: 80 } }) });

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

useLoadTexture

Loads an image to draw with, and hands it back at once, still loading: a sprite made with it appears by itself when the file arrives, so nothing has to wait for it.

useLoadTexture(options: TUseLoadTextureOptions) => TTexture
Example
export const Level: TSceneFn = () => {
    const hero = useLoadTexture({ src: '/assets/hero.png', key: 'hero' });
    createSprite({ texture: hero });
    return createScene();
};
Full entry in the reference

useLoadTrackerSong

Loads a song made in a NES tracker, FamiTracker or FamiStudio, from its text export, and plays it on the engine's NES: the same song useLoadSong gives, for useSong, with its own tempo, key, pan and beats.

useLoadTrackerSong(options: TUseLoadTrackerSongOptions) => TSongFile
Example
const theme = useLoadTrackerSong({ src: '/music/theme.txt' });
useSong(theme, { autoplay: true });
Full entry in the reference

Tags

useTag

Gives the tag name, to put on things, take off, ask about and find: what something is, 'enemy', 'coin', 'damageable', as many as it likes.

useTag(name: string) => TTag
Example
const Enemy = () => {
    useTag('enemy').add(useSelf());
    createSprite({ key: 'bat' });
};

export const Level: TSceneFn = () => {
    const coins = useTag('coin');
    coins.add(createSprite({ key: 'coin', transform: { x: 80, y: 60 } }));
    useUpdate(() => {
        if (coins.all().length === 0) console.log('all taken');
    });
    return createScene();
};
Full entry in the reference

Hitboxes

useCollisionBetween

Calls callback for every thing of kind a touching one of kind b, every frame they touch: a rule of the scene, shots against enemies, the player against coins.

useCollisionBetween(a: A, b: B, callback: (a: TCollisionMatched<A>, b: TCollisionMatched<B>) => void) => () => void
Example
declare const Bat: (props: { x: number }) => { hurt(damage: number): void };

export const Cave: TSceneFn = () => {
    useSpawn(Bat)({ x: 200 });
    useCollisionBetween('shot', Bat, (shot, bat) => {
        destroy(shot);
        bat.api.hurt(1);
    });
    return createScene();
};
Full entry in the reference

useCollisionWith

Calls callback with each thing the object being built touches, of one kind: a bullet and the enemies, the player and the coins.

useCollisionWith(match: M, callback: (other: TCollisionMatched<M>) => void, options: TCollisionWithOptions) => () => void
Example
declare const Bat: () => { hurt(damage: number): void };

const Bullet = ({ x }: { x: number }) => {
    const self = useSelf();
    createSprite({ width: 4, height: 4, transform: { x, y: 200 } });
    useHitbox();
    useCollisionWith(Bat, (bat) => {
        destroy(self);
        bat.api.hurt(1);
    });
};
Full entry in the reference

useHitbox

Gives this object a part that can be touched: what useCollisionWith, useCollisionBetween and collisionBetween measure it by instead of its picture.

useHitbox(options: THitboxOptions) => THitbox
Example
const Hero = () => {
    const keys = useKeyboard();
    createSprite({ key: 'hero', transform: { x: 40, y: 160 } });
    useTag('player').add(useSelf());
    const body = useHitbox({ width: 10 });

    useUpdate(() => {
        // A hero 24 pixels tall, crouching: 12 tall, and 6 lower so the feet stay where they were.
        const crouching = keys.isDown('ArrowDown');
        body.height = crouching ? 12 : undefined;
        body.y = crouching ? 6 : 0;
    });
};
Full entry in the reference

Physics

useCharacterBody2dnacatamalon/physics2d

Makes this object a platformer's character: the game says how fast it goes, and the world stops it at the map's walls, holds it on ledges and slopes, and lets it push what the simulation moves.

useCharacterBody2d(options: TCharacterOptions2d) => TCharacterBody2d
Example
import { createSprite, useKeyboard, useUpdate } from 'nacatamalon';
import { useCharacterBody2d } from 'nacatamalon/physics2d';

const Hero = () => {
    createSprite({ key: 'hero', transform: { x: 40, y: 100 } });
    const body = useCharacterBody2d({ width: 12, height: 24 });
    const keys = useKeyboard();

    useUpdate(() => {
        const walk = (keys.isDown('ArrowRight') ? 1 : 0) - (keys.isDown('ArrowLeft') ? 1 : 0);
        body.velocity.x = walk * 90;
        if (keys.justPressed('x') && body.isOnGround) body.velocity.y = -300;
        if (keys.justPressed('ArrowDown') && body.isOnOneWay && !body.isOnLadder) body.dropThrough();

        // Onto a ladder with up in front of it, or with down standing on its top.
        const up = keys.isDown('ArrowUp') && !body.isOnOneWay;
        const down = keys.isDown('ArrowDown') && body.isOnOneWay;
        if (body.isOnLadder && (up || down)) body.climbing = true;
        if (body.climbing) body.velocity.y = keys.isDown('ArrowUp') ? -60 : keys.isDown('ArrowDown') ? 60 : 0;
    });
};
Full entry in the reference

useJoint2dnacatamalon/physics2d

Joins two objects' bodies, or one to a point of the world when b is null: the planks of a bridge, a pendulum on its nail, a platform on a spring, a door on its hinge.

useJoint2d(a: TGameObject, b: TGameObject | null, joint: TJoint2d) => TJointHandle2d
Example
import { createScene, createSprite, usePhysicsBody2d, usePhysicsWorld2d, useSpawn } from 'nacatamalon';
import { useJoint2d } from 'nacatamalon/physics2d';
import type { TGameObject, TSceneFn } from 'nacatamalon';

// A bridge of eight planks between two ledges, pinned to the world at both ends.
const Plank = (x: number) => {
    createSprite({ key: 'plank', transform: { x, y: 120 } });
    usePhysicsBody2d({ body: 'dynamic', collider: { shape: 'rect', width: 16, height: 4 } });
};

export const River: TSceneFn = () => {
    usePhysicsWorld2d();
    const spawnPlank = useSpawn(Plank);
    const planks: TGameObject[] = [];
    for (let i = 0; i < 8; i++) planks.push(spawnPlank(72 + i * 16));

    useJoint2d(planks[0], null, { type: 'hinge', at: { x: 64, y: 120 } });
    for (let i = 1; i < planks.length; i++) {
        useJoint2d(planks[i - 1], planks[i], { type: 'hinge', at: { x: 64 + i * 16, y: 120 } });
    }
    useJoint2d(planks[7], null, { type: 'hinge', at: { x: 64 + 8 * 16, y: 120 } });
    return createScene();
};
Full entry in the reference

usePhysicsBody2d

Gives this object a flat shape to collide with.

usePhysicsBody2d(options: TPhysicsBody2dOptions) => TPhysicsBody2d
Example
const BROWN = getColor('#8b5a2b');

const Crate = (x: number, y: number) => {
    createSprite({ tint: BROWN, width: 24, height: 24, transform: { x, y } });
    usePhysicsBody2d({ body: 'dynamic', collider: { shape: 'rect', width: 24, height: 24 }, bounce: 0.2 });
};
Full entry in the reference

usePhysicsWorld2d

Opens the flat simulation for this scene, and says how hard things fall.

usePhysicsWorld2d(options: { id, gravity }) => TPhysicsWorld2d
Example
export const Level: TSceneFn = () => {
    usePhysicsWorld2d({ gravity: { x: 0, y: 900 } });
    // ...then objects with usePhysicsBody2d, which fall in it.
    return createScene();
};
Full entry in the reference

useRetroBody2d

Gives this object a retro body: one that never turns, moved in pixels a fixed step at a time and stopped against the others axis by axis, the way the old games did.

useRetroBody2d(options: TRetroBody2dOptions) => TRetroBody2d
Example
const Ball = (x: number, y: number) => {
    createSprite({ key: 'ball', transform: { x, y } });
    useRetroBody2d({ body: 'dynamic', collider: { shape: 'circle', radius: 4 }, bounce: 1, gravityScale: 0 });
};
Full entry in the reference

useRetroWorld2d

Opens the retro simulation for this scene, and says how hard things fall: in pixels per second squared with +y down, like the full flat simulation's.

useRetroWorld2d(options: Partial<Omit<TRetroWorld2d, '_type'>>) => TRetroWorld2d
Example
export const Level: TSceneFn = () => {
    useRetroWorld2d({ gravity: { x: 0, y: 900 } });
    // ...then objects with useRetroBody2d, which fall in it.
    return createScene();
};
Full entry in the reference

useSoftBody2dnacatamalon/physics2d

Makes the object being built a soft body in the scene's 2D world: something that squashes, wobbles and rolls rather than keeping its shape.

useSoftBody2d(options: TSoftBodyOptions2d) => TSoftBody2d
Example
import { createGame, createPolygon, createScene, useKeyboard, usePhysicsWorld2d, useSpawn, useTransform, useUpdate } from 'nacatamalon';
import { installPhysics2d, useSoftBody2d } from 'nacatamalon/physics2d';

installPhysics2d();

// A green blob that hops with space.
const Blob = () => {
    useTransform({ x: 160, y: 40 });
    const ring = Array.from({ length: 16 }, (_, i) => ({ x: Math.cos(i / 16 * Math.PI * 2) * 20, y: Math.sin(i / 16 * Math.PI * 2) * 20 }));
    const polygon = createPolygon({ points: ring, tint: '#5bd75b' });
    const blob = useSoftBody2d({ shape: 'disk', radius: 20, polygon });
    const keys = useKeyboard();
    useUpdate(() => {
        if (keys.justPressed(' ')) blob.kick(0, -300);
    });
};

const Level = () => {
    usePhysicsWorld2d();
    useSpawn(Blob)();
    return createScene();
};

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

useTileBody2d

Makes this object a platformer's character that walks on the scene's maps, with no physics engine: the game says how fast it goes, and the map stops it at walls, holds it on ledges and slopes, lets it climb ladders and carries it on belts.

useTileBody2d(options: TCharacterShape2d) => TCharacterBody2d
Example
const Hero = () => {
    createSprite({ key: 'hero', transform: { x: 40, y: 100 } });
    const body = useTileBody2d({ width: 12, height: 24 });
    const keys = useKeyboard();

    useUpdate(() => {
        const walk = (keys.isDown('ArrowRight') ? 1 : 0) - (keys.isDown('ArrowLeft') ? 1 : 0);
        body.velocity.x = walk * 90;
        if (keys.justPressed('x') && body.isOnGround) body.velocity.y = -300;
        if (keys.justPressed('ArrowDown') && body.isOnOneWay && !body.isOnLadder) body.dropThrough();

        // Onto a ladder with up in front of it, or with down standing on its top.
        const up = keys.isDown('ArrowUp') && !body.isOnOneWay;
        const down = keys.isDown('ArrowDown') && body.isOnOneWay;
        if (body.isOnLadder && (up || down)) body.climbing = true;
        if (body.climbing) body.velocity.y = keys.isDown('ArrowUp') ? -60 : keys.isDown('ArrowDown') ? 60 : 0;
    });
};
Full entry in the reference

Capture

useCapture

A camera for the game itself: takes photos of what the player sees, the whole screen or a part of it, for a photography game, an album, a "spot the difference", a sticker of the boss beaten.

useCapture() => TCapture
Example
const capture = useCapture();
const shutter = useAction('shoot');
// The print the last photo shows on, made once in the body.
const film = createPixels(96, 72);
const print = createPixelTexture(film);
createSprite({ texture: print, transform: { x: 270, y: 50 } });
let score = 0;

useUpdate(() => {
    if (shutter.justPressed()) {
        void capture({ region: 'Viewfinder', hide: ['Hud'], width: 96, height: 72 }).then((photo) => {
            const bird = photo.boxes.find((b) => b.name === 'Bird');
            score += bird ? Math.round(bird.seen * 100) : 0;
            film.data.set(photo.data);
            updatePixelTexture(print);
        });
    }
});
Full entry in the reference

Render

useRenderStyle

Draws this scene in a style: how its models' materials are drawn when they do not say (at every pixel, swimming, shivering) and the full-screen effects it is seen through, in place of the game's style (createGame({ style })).

useRenderStyle(style: TRenderStyle | null) => TRenderStyleHandle
Example
const Museum = () => {
    const keys = useKeyboard();
    const style = useRenderStyle(RENDER.STYLES.cgi);
    useStudio();
    // ...
    useUpdate(() => {
        if (keys.justPressed('p')) style.set(RENDER.STYLES.ps1);
    });
    return createScene();
};
Full entry in the reference

Math

useRandomnacatamalon/math

The random numbers of this game.

useRandom() => TRandomHandle
Example
export const Level: TSceneFn = () => {
    const random = useRandom();

    for (let i = 0; i < 20; i++) {
        createSprite({ key: 'tree', transform: { x: random.rand(0, 480), y: random.rand(0, 320) } });
    }

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

Debug

useHelperAxis

Draws the three axes as coloured lines from where it is placed: X red, Y green, Z blue, the colours every 3D tool uses.

useHelperAxis(options: TUseHelperAxisOptions) => TLines
Example
const Level = () => {
    useCamera3d({ projection: 'perspective', fov: 60, transform: { y: 1, z: 4, rotationX: -0.2 } });
    useHelperAxis({ size: 2, negative: true });
    return createScene();
};
Full entry in the reference

useHelperGrid

Draws a floor grid on the ground plane, the one every 3D editor shows, with its middle lines in the colours of the X and Z axes.

useHelperGrid(options: TUseHelperGridOptions) => TLines
Example
const Level = () => {
    useCamera3d({ projection: 'perspective', fov: 60, transform: { y: 4, z: 8, rotationX: -0.45 } });
    useHelperGrid({ half: 5 });
    return createScene();
};
Full entry in the reference

useLines

Draws any lines you like.

useLines(options: TUseLinesOptions) => TLines
Example
declare const target: { x: number; y: number; z: number };

const Level = () => {
    useCamera3d({ projection: 'perspective', fov: 60, transform: { z: 6 } });
    const path = useLines();

    useUpdate(() => {
        // One yellow line from the origin to wherever the enemy is heading.
        setLines(path, [{ from: { x: 0, y: 0, z: 0 }, to: target, color: '#ffcc00' }]);
    });

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

Net

useNetnacatamalon/net

The network, for a scene of an online game.

useNet() => TNetHandle
Example
import { createScene, createText, useUpdate, useKeyboard, type TSceneFn } from 'nacatamalon';
import { useRandom } from 'nacatamalon/math';
import { useNet } from 'nacatamalon/net';

export const Pond: TSceneFn = () => {
    const net = useNet();
    const random = useRandom();
    const coins = new Map<string, number>();

    if (net.role === 'server') {
        // Decided here and nowhere else, with the server's own luck.
        net.onJoin((player) => coins.set(player, 100));
        net.onMessage('pull', (_data, from) => {
            if (from === null || !random.chance(0.5)) return; // nothing bit
            const now = (coins.get(from) ?? 0) + 10;
            coins.set(from, now);
            net.sendTo(from, 'coins', now);
        });
    } else {
        const label = createText({ text: 'COINS 100' });
        const keys = useKeyboard();
        net.connect('wss://example.com', { room: 'pond' });
        net.onMessage<number>('coins', (amount) => { label.text = `COINS ${amount}`; });
        useUpdate(() => {
            if (net.status === 'online' && keys.justPressed(' ')) net.send('pull');
        });
    }
    return createScene();
};
Full entry in the reference

useNetSpawnnacatamalon/net

A spawner for objects every game in the room sees: the server calls it, and the object is made there and, with the same arguments, in every player's game, now and for whoever comes later; when the server destroys it, it goes everywhere.

useNetSpawn(kind: string, component: (args: TArgs) => TApi, options: Omit<TSpawnOptions, 'name'>) => (args: TArgs) => TGameObject<TApi>
Example
import { createScene, createShapes, destroy, useTransform, type TGameObject, type TSceneFn } from 'nacatamalon';
import { useNet, useNetSpawn } from 'nacatamalon/net';

const Coin = (x: number, y: number) => {
    useTransform({ x, y });
    createShapes({ shapes: [{ type: 'circle', x: 0, y: 0, radius: 4, fill: '#ffd040' }] });
};

export const Field: TSceneFn = () => {
    const net = useNet();
    const spawnCoin = useNetSpawn('coin', Coin);
    if (net.role === 'server') {
        const coin: TGameObject = spawnCoin(40, 30);
        net.onMessage('take', () => destroy(coin));
    }
    return createScene();
};
Full entry in the reference

useRoomStorenacatamalon/net

This game's store of a declaration made with createRoomStore: the room's own in the room, a copy the room keeps up to date in a player's game.

useRoomStore(decl: TRoomStoreDecl<S>) => TRoomStore<S>
Example
import { createScene } from 'nacatamalon';
import { createRoomStore, useRoomStore } from 'nacatamalon/net';

const round = createRoomStore({ key: 'round', state: { number: 1, left: 90 } });

const Arena = () => {
    const clock = useRoomStore(round);
    clock.watch((s) => s.left, (left) => { console.log(`${left} s left`); });
    return createScene();
};
Full entry in the reference

useSharednacatamalon/net

Makes the object being built one every game in the room sees: the server decides where it is and what its fields hold, and each player's game shows it there a moment later, gliding between what it was told.

useShared(options: TSharedOptions<F>) => TShared<F>
Example
import { createScene, createSprite, destroy, useSelf, type TGameObject, type TSceneFn } from 'nacatamalon';
import { useNet, useNetSpawn, useShared } from 'nacatamalon/net';

const SPEED = 80;

// A player's avatar: theirs to move, everyone's to see.
const Avatar = (player: string) => {
    const self = useSelf();
    createSprite({ texture: 'avatar' });
    const shared = useShared({
        owner: player,
        fields: { score: 0 },
        move: (input, dt) => {
            const { x, y } = input.direction('left', 'right', 'up', 'down');
            self.transform!.x += x * SPEED * dt;
            self.transform!.y += y * SPEED * dt;
        },
    });
    return shared;
};

export const Arena: TSceneFn = () => {
    const net = useNet();
    const spawnAvatar = useNetSpawn('avatar', Avatar);
    if (net.role === 'server') {
        const avatars = new Map<string, TGameObject>();
        net.onJoin((player) => avatars.set(player, spawnAvatar(player)));
        net.onLeave((player) => {
            const avatar = avatars.get(player);
            if (avatar !== undefined) destroy(avatar);
        });
    }
    return createScene();
};
Full entry in the reference