Lifecycle
Volver a la referencia

Lifecycle

What runs every frame, and what runs when a scene is taken down.

8 símbolos

useCleanupfunctionhooknacatamalon

useCleanup(cleanup: () => void) => void

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

For what you started outside the engine: a window listener, a setInterval, a request. What the engine made goes away by itself. destroy is what sets it off.

Parámetros

cleanup() => void

What to undo. It receives nothing and is called exactly once.

Ejemplo

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));
};
Ver el código · hooks/scene/use_cleanup.ts:28

useLateUpdatefunctionhooknacatamalon

useLateUpdate(callback: (delta: number, time: number) => void) => void

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

It exists for code that reads where something ended up rather than moving it: a camera that follows the player, a marker over an enemy's head, a shadow under a sprite, a sword held in a hand. In useUpdate the scene runs before the objects inside it, so a camera there reads the player where it was before it moved this frame, and the player is drawn one step away from where the camera put it. While the player runs at a steady speed the gap stays the same and nobody notices; when it starts, stops, lands or hits a wall the gap changes from one frame to the next, and the character shakes against the screen. Here everything has already moved, tweens and physics included, so what is read is what will be drawn.

The rule is short: move things in useUpdate, follow them in useLateUpdate.

It receives the same delta and time as useUpdate in the same frame, and it follows the same rules: it stops while the scene is paused, an object spawned this frame starts on the next one, and an object destroyed during the updates does not run it.

Call it in the scene body, next to the sprites. It only registers the function, it does not run it.

Parámetros

callback(delta: number, time: number) => void

What to run each frame, once the updates are over. delta is the seconds since the previous frame, and time the seconds since the scene started.

Ejemplo

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();
};
Ver el código · hooks/loop/use_late_update.ts:54

useReadyfunctionhooknacatamalon

useReady(callback: () => void) => void

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

A body runs as its object is made, and an object is made before the ones inside it. In a scene written in code that rarely shows, because the body makes its children itself; in a scene laid out as a document it always does: a behaviour on the scene's root runs before the boxes under it are there, so findObject(root, 'Pitcher') in its body finds nothing. Inside useReady it finds it.

For something spawned later (a useSpawn called from a useUpdate or a click), it runs as soon as that thing and everything inside it are built, before the spawner's call returns.

It runs with its object as the one being built, so hooks called inside it (a useUpdate that needs what was found) belong to that object. Register as many as you like: they run in the order they were registered, parents' before children's.

Parámetros

callback() => void

What to do once everything is there. It receives nothing and runs exactly once.

Ejemplo

// 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;
        });
    });
});
Ver el código · hooks/scene/use_ready.ts:44

useSceneTransitionEndfunctionhooknacatamalon

useSceneTransitionEnd(callback: () => void) => void

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

A scene that comes in with a transition (change('Level', { transition: iris(0.6) })) starts at once, so its loading starts too, and waits behind the cover: its body and its useReady have already run, but it is not seen. Its clock does not move while it waits, so a timer or a tween started in useReady waits with it, and so does a sound set to autoplay, until the swap. What does not wait is what is started by hand and keeps real time: a play(), a vibration. Started here, they begin when the player can see the scene. So does handing over the controls once nothing covers the level.

Without a transition it runs on the scene's first frame, before its first update, so a scene does the same with its transition or without it. In something spawned once the scene is already on screen, it runs at the start of the next frame.

It runs with its object as the active one, so hooks called inside it belong to that object. If the scene stops before it is seen, it never runs.

Parámetros

callback() => void

What to do once the scene is in full view. It receives nothing and runs exactly once.

Ejemplo

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) });
Ver el código · hooks/scene/use_scene_transition_end.ts:43

useTimerfunctionhooknacatamalon

useTimer() => TTimer

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

It is what setTimeout and setInterval would be if they knew about the game. The wait is counted in the same seconds as useUpdate's delta, so it stops while the scene is paused, follows timeScale, and is gone when the object that asked for it is: a cutscene that waits two seconds still waits two seconds after a pause, and a timer of a scene that ended never fires into the next one. A setTimeout does none of the three.

Call useTimer in the body, like any hook. What it returns can be used from anywhere after that, an update, a click or another timer, so a sequence is just calls that schedule the next step.

Several calls due in the same frame run in the order they were due, so a long frame cannot swap the steps of a sequence. One scheduled from inside another runs on a later frame at the soonest.

Ejemplo

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();
};
Ver el código · hooks/timer/use_timer.ts:70

useUpdatefunctionhooknacatamalon

useUpdate(callback: (delta: number, time: number) => void) => void

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

The function you pass receives delta: how many seconds the last frame took, about 0.016 on a 60 Hz screen and about 0.008 on a 120 Hz one. Multiply by it whenever something moves or counts down, and the game runs at the same speed on every machine. Ignore it, and the same game is twice as fast on a better screen.

It also receives time: the seconds the scene has been running. It is what a sine wave, a blink or a pulse wants, so nothing needs its own counter. It is game time, like delta: it stops while the scene is paused, follows timeScale, and starts again from zero when the scene does. Every object in the scene reads the same clock, so two things that pulse together stay together, whenever each one was spawned.

Call it in the scene body, next to the sprites. It only registers the function, it does not run it: from then on the game loop calls it every frame, and stops when the scene does.

Parámetros

callback(delta: number, time: number) => void

What to run each frame. delta is the seconds since the previous frame, and time the seconds since the scene started.

Ejemplo

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();
};
Ver el código · hooks/loop/use_update.ts:48

TTimerHandletypenacatamalon

One waiting call, handed back by after and every so it can be called off.

Propiedades

cancel
doneboolean

Whether it is over: an after that has run, or anything cancelled. An every is never done on its own.

Ver el código · hooks/timer/types/t_timer.ts:8