melonJS
    Preparing search index...

    Variable stateConst

    state: {
        CREDITS: 7;
        DEFAULT: 9;
        GAME_END: 5;
        GAMEOVER: 4;
        LOADING: 0;
        MENU: 1;
        PLAY: 3;
        READY: 2;
        SCORE: 6;
        SETTINGS: 8;
        USER: 100;
        change(
            stateId: number,
            forceChange?: boolean,
            ...extraArgs: unknown[],
        ): void;
        current(): Stage | undefined;
        freeze(duration: number, music?: boolean): Promise<void>;
        get(stateId?: number): Stage | undefined;
        isCurrent(stateId: number): boolean;
        isPaused(): boolean;
        isRunning(): boolean;
        pause(music?: boolean): void;
        reload(forceChange?: boolean, ...extraArgs: unknown[]): void;
        restart(music?: boolean): void;
        resume(music?: boolean): void;
        set(stateId: number, stage: Stage, start?: boolean): void;
        setTransition(stateId: number, enable: boolean): void;
        stop(shouldPauseTrack?: boolean): void;
        transition(
            effect: "fade" | "mask" | "pixelate",
            color: string,
            duration?: number,
            shape?: number | MaskShape,
            options?: { center?: MaskCenter; invert?: boolean },
        ): void;
    } = ...

    a State Manager (state machine)

    Type Declaration

    • CREDITS: 7

      default state ID for Credits Stage

    • DEFAULT: 9

      default state ID for the default Stage (the default stage is the one running as soon as melonJS is started)

    • GAME_END: 5

      default state ID for Game End Stage

    • GAMEOVER: 4

      default state ID for Game Over Stage

    • LOADING: 0

      default state ID for Loading Stage

    • default state ID for Menu Stage

    • PLAY: 3

      default state ID for Play Stage

    • READY: 2

      default state ID for "Ready" Stage

    • SCORE: 6

      default state ID for High Score Stage

    • SETTINGS: 8

      default state ID for Settings Stage

    • USER: 100

      default state ID for user defined constants

      const STATE_INFO = state.USER + 0;
      const STATE_WARN = state.USER + 1;
      const STATE_ERROR = state.USER + 2;
      const STATE_CUTSCENE = state.USER + 3;
    • change: function
      • change the game/app state

        With a transition (see state.transition), the state changes once the transition covers the screen. A change asked for until then is made by that same transition rather than a second one: it switches to the last state asked for, with the last arguments given. A change to a state whose transition is off (see state.setTransition) does not wait for it, and the cover comes down as the state changes.

        Parameters

        • stateId: number

          State ID (see constants)

        • OptionalforceChange: boolean = false

          if true the state will be changed immediately (without waiting for the next frame); ignored when a transition makes the change

        • ...extraArgs: unknown[]

          extra arguments to be passed to the reset functions

        Returns void

        // The onResetEvent method on the play screen will receive two args:
        // "level_1" and the number 3
        state.change(state.PLAY, false, "level_1", 3);
        // asked twice, by a key pressed twice on a menu: one transition, to PLAY
        state.transition("fade", "#000", 250);
        state.change(state.PLAY);
        state.change(state.PLAY);
    • current: function
      • return a reference to the current stage
        useful to call a object specific method

        Returns Stage | undefined

        the current Stage instance, or undefined if no stage is active

    • freeze: function
      • Freeze the current stage for a fixed duration, then automatically resume. Useful for hit-stop / hit-pause effects on impact.

        Behaviour notes:

        • If freeze() is called again while a freeze is already active, the freeze is extended to whichever end-time is later (calls do not stack). The music flag from the initial call is preserved.
        • If the game was already paused when freeze() was called, the freeze timer will not unpause it on expiry — the game stays paused.
        • Calling state.resume() or state.stop() while a freeze is active cancels the timer and resolves the returned promise immediately.
        • The freeze is also cancelled when the window loses focus (BLUR) since the hit-stop's "moment" is short enough that the user has missed it by the time they return. The regular pauseOnBlur behaviour still keeps the game paused while away.
        • Negative, NaN, and Infinity durations silently no-op.

        Parameters

        • duration: number

          duration of the freeze in milliseconds

        • Optionalmusic: boolean = false

          also pause the current music track during the freeze

        Returns Promise<void>

        a Promise that resolves once the freeze ends (or is cancelled)

        // simple hit-stop on impact
        state.freeze(80);

        // chain VFX after the freeze
        await state.freeze(120);
        spawnImpactParticles();
    • get: function
      • returns the stage associated with the specified state (or the current one if none is specified)

        Parameters

        • OptionalstateId: number = _state

          State ID (see constants)

        Returns Stage | undefined

        the Stage instance associated with the given state ID, or undefined

    • isCurrent: function
      • return true if the specified state is the current one

        Parameters

        • stateId: number

          State ID (see constants)

        Returns boolean

        true if the specified state is the current one

    • isPaused: function
    • isRunning: function
    • pause: function
      • pause the current stage

        Parameters

        • Optionalmusic: boolean = false

          pause current music track on screen pause

        Returns void

    • reload: function
      • Build the current stage again, for a "play again" button, a level restart or a retry: what state.change does when it switches to another state (the stage's onDestroyEvent, the world reset, then its onResetEvent), for the state already running, which change() leaves alone. It runs without the transition set with state.transition.

        Parameters

        • OptionalforceChange: boolean = false

          if true the stage is built again at once; otherwise on the next frame, as with change()

        • ...extraArgs: unknown[]

          the arguments passed to onResetEvent; left out, the ones the current state was last entered with

        Returns void

        when no state has been entered yet

        // a button on the game-over card
        new UITextButton(x, y, { text: "Play again", onClick: () => state.reload() });
        // the same level again, or the next one
        state.reload(false, "level1");
    • restart: function
      • Restart the current stage from a full stop.

        Parameters

        • Optionalmusic: boolean = false

          resume current music track on screen resume

        Returns void

    • resume: function
      • resume the current stage

        Parameters

        • Optionalmusic: boolean = false

          resume current music track on screen resume

        Returns void

    • set: function
      • associate the specified state with a Stage

        Parameters

        • stateId: number

          State ID (see constants)

        • stage: Stage

          Instantiated Stage to associate with state ID

        • Optionalstart: boolean = false

          if true the state will be changed immediately after adding it.

        Returns void

        class MenuScreen extends Stage {
        onResetEvent(app) {
        // Load background image
        app.world.addChild(
        new ImageLayer(0, 0, {
        image : "bg",
        z: 0 // z-index
        })
        );

        // Play music
        audio.playTrack("menu");
        }

        onDestroyEvent() {
        // Stop music
        audio.stopTrack();
        }
        }

        state.set(state.MENU, new MenuScreen());
    • setTransition: function
      • enable/disable the transition to a particular state (by default enabled for all)

        Parameters

        • stateId: number

          State ID (see constants)

        • enable: boolean

          true to enable transition, false to disable

        Returns void

    • stop: function
      • Stop the current stage.

        Parameters

        • OptionalshouldPauseTrack: boolean = false

          pause current track on screen stop.

        Returns void

    • transition: function
      • specify a global transition effect

        Parameters

        • effect: "fade" | "mask" | "pixelate"

          "fade" for a color fade, "mask" for a shape-based mask transition, "pixelate" for the screen breaking up into ever larger blocks, changing behind the largest, and coming back sharp (see PixelateTransitionEffect). A pixelate transition is a shader effect: on the Canvas renderer it does nothing, and the state changes directly.

        • color: string

          a CSS color value (not used by "pixelate")

        • Optionalduration: number = 1000

          expressed in milliseconds, for each half: the cover, then the reveal

        • Optionalshape: number | MaskShape

          for "mask" (required) the mask shape: an Ellipse or Polygon (unit-sized, centred on the origin), an image or the name of a preloaded one (its silhouette), or a Sprite (the silhouette of the frame it shows when the transition starts); see MaskEffect. A sprite the game keeps for itself (in no level, or persistent) is kept with the transition, and shapes every change. One that is part of the level shapes the next change, which destroys it, and is then let go: later changes are an iris until it is set again. For "pixelate", the size of the largest blocks, in screen pixels (32 by default)

        • Optionaloptions: { center?: MaskCenter; invert?: boolean }

          for "mask" only

          • Optionalcenter?: MaskCenter

            where the shape closes and opens: a renderable, such as the player, at the place it is drawn when the transition starts, or a point on screen. The centre of the screen by default. The reveal opens from the same place. A renderable is kept or let go as a sprite shape is

          • Optionalinvert?: boolean

            make the shape the cover rather than the window: filled with the color, it grows out of center until it covers the screen, and shrinks away to reveal it

        Returns void

        // classic fade to black
        state.transition("fade", "#000", 500);
        // iris (circle) mask transition
        state.transition("mask", "#000", 500, new Ellipse(0, 0, 1, 1));
        // diamond mask transition
        state.transition("mask", "#000", 400, new Polygon(0, 0, [
        { x: 0, y: -1 }, { x: 1, y: 0 },
        { x: 0, y: 1 }, { x: -1, y: 0 },
        ]));
        // a star wipe, from a preloaded silhouette image
        state.transition("mask", "#000", 500, "star_mask");
        // the player's own silhouette, closing on the player: set right before
        // the change, as the player of one level is not the next one's
        state.transition("mask", "#000", 500, player, { center: player });
        state.change(state.GAME_END);
        // a sprite of the game's own, in no level: set once, for every change
        const logo = atlas.createSpriteFromName("logo");
        state.transition("mask", "#000", 500, logo);
        // a black circle growing out of the player until it covers the screen
        state.transition("mask", "#000", 400, new Ellipse(0, 0, 1, 1), {
        center: player,
        invert: true,
        });
        // the screen breaks up into 32 pixel blocks, and comes back
        state.transition("pixelate", "#000", 300);
        // into 16 pixel blocks
        state.transition("pixelate", "#000", 300, 16);