State
Volver a la referencia

State

The state an object keeps while it lives, and code that runs when it changes.

10 símbolos

useDatafunctionhooknacatamalon

useData(initial: T) => [TDataRecord<T>, TDataSetter<T>]

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

Read it as data.value, change it with the setter, and have something react to it with useWatch(fn, [data]). Two things far apart can share one: whoever makes it can hand it to whatever it builds, and each of them watches it without knowing about the others.

Change it through the setter, not with data.value = x. Writing to the field works and is read back correctly, but nothing is told about it, so a useWatch on it will not run.

It is also what gets saved. A scene written down carries this state and gives it back when the scene is opened again, which is what makes a saved game a saved game and not a fresh start. Keep in it the kind of thing a file can hold: numbers, text, lists and plain objects. A texture or a function is not something a file can keep.

Call it in the scene body, like the rest of the hooks.

Parámetros

initialT

What it holds before anything changes it.

Ejemplo

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();
};
Ver el código · hooks/state/use_data.ts:223

useStateMachinefunctionhooknacatamalon

useStateMachine(initial: NoInfer<S>, states: Record<S, TStateDef>, options?: TStateMachineOptions<P>) => TStateMachine<S>

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.

Each state says what it does on the way in (onEnter), every frame it lasts (onUpdate) and on the way out (onExit), and the machine is in exactly one of them at a time. The names come from the object, so go('jum') is a type error.

It is a hook like the rest, so it works wherever one does: the body of a scene, of a piece made with useSpawn (a Hero), or of a behaviour. It belongs to that object: it runs with its updates, in the order it was written among them, stops in a paused scene, and goes when the object goes.

The state it is in is saved with the object, like useData, and a scene opened again starts in it (calling its onEnter), with the time it had been there.

States inside a state. Given { parent, state }, the machine lives inside that state of another: it enters its initial when the other enters that state, and leaves when the other leaves it, from the inside out (onExit of its state, then of the other's) and in from the outside in. Each frame the other's onUpdate runs first, so what holds for the whole state (a guard that has lost the hero leaves combat, whichever move it was in) is written once there, and then its own. Each has its own names, time and onChange; a change asked for from inside a change of any of them waits until that change is over. It can live in the same object as the other or in a piece of its own, and another machine can live inside one of its states in turn.

Call it in the body, like the rest of the hooks.

Parámetros

initialNoInfer<S>

The state it starts in, one of the names in states.

statesRecord<S, TStateDef>

Each state by name, with what it does.

optionsopcionalTStateMachineOptions<P>

To live inside a state of another machine: { parent, state }.

Ejemplo

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();
};

Ejemplo

declare const banner: TText;
declare const bossDefeated: TGameSignal<void>;

// A scene's own phases.
export const Boss: TSceneFn = () => {
    const scene = useScene();
    const fight = useStateMachine('intro', {
        intro: {
            onEnter: () => { banner.text = 'READY?'; },
            onUpdate: () => { if (fight.time > 2) fight.go('fight'); },
        },
        fight: {
            onEnter: () => { banner.text = ''; },
        },
        won: {
            onEnter: () => { banner.text = 'YOU WIN'; },
            onUpdate: () => { if (fight.time > 3) scene.change('Map'); },
        },
    });

    useSignal(bossDefeated, () => fight.go('won'));
    useWatch(() => console.log('now', fight.state), [fight]);

    return createScene();
};

Ejemplo

declare const lostHero: () => boolean;

// States inside a state: the guard is calm or in combat, and each has moves of its own.
const guard = useStateMachine('calm', {
    calm: {},
    combat: {
        // Holds for every move of the combat, written once.
        onUpdate: () => { if (lostHero()) guard.go('calm'); },
    },
});

const calm = useStateMachine('patrol', {
    patrol: {},
    search: { onUpdate: () => { if (calm.time > 2) calm.go('back'); } },
    back: {},
}, { parent: guard, state: 'calm' });

const combat = useStateMachine('approach', {
    approach: {},
    swing: {},
    recover: { onUpdate: () => { if (combat.time > 0.5) combat.go('approach'); } },
}, { parent: guard, state: 'combat' });

// From anywhere: into combat, straight at a swing.
combat.go('swing');
Ver el código · hooks/state/use_state_machine.ts:334

useWatchfunctionhooknacatamalon

useWatch(fn: () => void, deps: typeOperator) => void

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

What goes in the list is the thing itself ([lives, texture]), not a reading of it: those objects are changed in place and never swap identity, so there would be nothing to compare. The engine keeps a count of how many times it has announced a change on each one, and this compares those counts once a frame.

The other side of that: a change the engine was not told about does not count. setLives(2) is announced and lives.value = 2 is not, exactly like React's rule about not assigning to state. Anything a game moves by hand, a transform above all, is changed in place all the time and is never announced, so it cannot be watched. Passing one is refused when the scene starts rather than accepted into a callback that would never run again.

A store counts as changed on any set or action, whatever it touched. To hear one value of it, straight away and even in pause, use useStore; to draw from several things at once, this.

The first run happens whether or not anything changed, so a scene does not need to write its starting state twice: once in the body and once in the watch.

It runs in the same pass as useUpdate and in the order written, so a scene in pause does not watch, the same way it does not update. A change made while it was paused is seen on the first frame after it resumes. If something has to be heard even in pause, that is what useStore and useSignal are for.

Two changes to the same thing in one frame are one run: what is compared is where things ended up, once a frame, not every step they took.

Parámetros

fn() => void

What to run. It takes nothing: read the things you listed.

depstypeOperator

What to watch. Changing what is in this list later has no effect: it is read once.

Ejemplo

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();
};
Ver el código · hooks/state/use_watch.ts:72

TDataRecordtypenacatamalon

State that belongs to one piece of the scene, handed back as an object you read .value from.

An object and not the value itself, because the body of a scene runs once: a plain value read there would be the value it had at that moment, for ever, no matter what happened afterwards. The object never changes identity, so reading .value later, inside useUpdate or a click, always gives what it holds now.

Propiedades

valueT
Ver el código · hooks/state/use_data.ts:157

TDataSettertypenacatamalon

TDataSetter: (next: T | (previous: T) => T | void) => void

How that state is changed. Three forms, and they are interchangeable:

  • the next value: setLives(2);
  • a function that returns the next value: setLives((n) => n - 1);
  • a function that changes it in place and returns nothing: setHero((h) => { h.x += 1; }).

The third is why the function may return nothing: when it does, what it was given is taken as already changed. That is the same shape a store's set has, so one habit covers both, while the returning form stays there for numbers and strings, where changing in place is not possible.

Whichever form is used, the change is announced, which is what useWatch is listening for.

Ver el código · hooks/state/use_data.ts:178

TStateDeftypenacatamalon

What one state of a useStateMachine does: on the way in, every frame it lasts, and on the way out. All three are optional, so a state that only waits to be left can be {}.

Propiedades

onEnteropcional() => void

Runs once, when the machine arrives in this state. For the starting state, on the first frame rather than while the body runs, so whatever the body made is there by then.

onUpdateopcional(delta: number) => void

Runs every frame the machine is in this state, in the same pass as useUpdate, with the seconds since the last frame. It does not run in a paused scene.

onExitopcional() => void

Runs once, when the machine leaves this state for another. Not when its object is destroyed: that is not a change of state, and useCleanup is there for it.

Ver el código · hooks/state/use_state_machine.ts:16

TStateGoOptionstypenacatamalon

How go can be asked to change state.

Propiedades

restartopcionalboolean

Leave and come back in when it is already in that state: onExit and onEnter run, and time starts again from 0. A second punch of a combo is this. Without it, going to the state it is in does nothing.

Ver el código · hooks/state/use_state_machine.ts:41

TStateMachinetypenacatamalon

A state machine made by useStateMachine: which state it is in, for how long, and the way to change it.

It can be watched: useWatch(fn, [machine]) runs whenever it changes state.

Propiedades

stateS

The state it is in now. A machine inside another's state (see TStateMachineOptions), while that state is not the other's: the state it will enter, its initial unless go asked for another.

activeboolean

Whether it is running. Always for a machine of its own; for one inside another's state, only while the other is in that state.

previousS | null

The state it was in before this one, or null while it has never changed.

timenumber

Seconds it has been in the state it is in. They go at the scene's speed and stand still while the scene is paused. 0 while it is not active.

go
is
onChange
Ver el código · hooks/state/use_state_machine.ts:60

TStateMachineOptionstypenacatamalon

Where a machine lives inside another: in one of its states. It runs only while the other is there, which is how a state gets states of its own.

It is driven by the other: it updates in the other's frame, at the speed of the other's scene, and stops when that scene is paused, wherever its own object is. One made while the other is already running (a piece spawned during play) comes in on the other's next frame, never in the middle of the body making it; until then go only picks where it will come in. Made while the other's scene is paused, that next frame is the first one after it resumes.

Propiedades

parentTStateMachine<P>

The machine it lives inside.

stateNoInfer<P>

The state of parent it lives in.

Ver el código · hooks/state/use_state_machine.ts:123

TWatchDeptypenacatamalon

TWatchDep: object

Something useWatch can be given to watch: state from useData, a store from createGameStore, or an asset from one of the useLoad… hooks.

Not a number or a string. Those are read once, where the list is written, and can never change afterwards, so watching one is always a mistake and is refused rather than accepted quietly.

Ver el código · hooks/state/use_watch.ts:15