Skip to main content

Engine <TKnownScenes>

The Excalibur Engine

The [[Engine]] is the main driver for a game. It is responsible for starting/stopping the game, maintaining state, transmitting events, loading resources, and managing the scene.

Implements

Index

Constructors

constructor

  • Creates a new game using the given [[EngineOptions]]. By default, if no options are provided, the game will be rendered full screen (taking up all available browser window space). You can customize the game rendering through [[EngineOptions]].

    Example:

    var game = new ex.Engine({
      width: 0, // the width of the canvas
      height: 0, // the height of the canvas
      enableCanvasTransparency: true, // the transparencySection of the canvas
      canvasElementId: '', // the DOM canvas element ID, if you are providing your own
      displayMode: ex.DisplayMode.FullScreen, // the display mode
      pointerScope: ex.PointerScope.Document, // the scope of capturing pointer (mouse/touch) events
      backgroundColor: ex.Color.fromHex('#2185d0') // background color of the engine
    });
    
    // call game.start, which is a Promise
    game.start().then(function () {
      // ready, set, go!
    });

    Type parameters

    • TKnownScenes: string = any

    Parameters

    Returns Engine<TKnownScenes>

Properties

publicreadonly_originalDisplayMode

_originalDisplayMode: DisplayMode

publicbackgroundColor

backgroundColor: Color

Sets the background color for the engine.

publicbrowser

browser: BrowserEvents

Excalibur browser events abstraction used for wiring to native browser events safely

publiccanvas

canvas: HTMLCanvasElement

Direct access to the engine's canvas element

publiccanvasElementId

canvasElementId: string

Direct access to the canvas element ID, if an ID exists

publicclock

clock: Clock

Direct access to the excalibur clock

publiccurrentFrameElapsedMs

currentFrameElapsedMs: number = 0

Returns the current frames elapsed milliseconds

publiccurrentFrameLagMs

currentFrameLagMs: number = 0

Returns the current frame lag when in fixed update mode

publicdebug

Access Excalibur debugging functionality.

Useful when you want to debug different aspects of built in engine features like

  • Transform
  • Graphics
  • Colliders

publicdirector

director: Director<TKnownScenes>

Scene director, manages all scenes, scene transitions, and loaders in excalibur

publicenableCanvasTransparency

enableCanvasTransparency: boolean = true

Sets the Transparency for the engine.

publicevents

events: EventEmitter<EngineEvents> = ...

Listen to and emit events on the Engine

publicoptionalfixedUpdateFps

fixedUpdateFps?: number

Optionally configure a fixed update fps, this can be desireable if you need the physics simulation to be very stable. When set the update step and physics will use the same elapsed time for each tick even if the graphical framerate drops. In order for the simulation to be correct, excalibur will run multiple updates in a row (at the configured update elapsed) to catch up, for example there could be X updates and 1 draw each clock step.

NOTE: This does come at a potential perf cost because each catch-up update will need to be run if the fixed rate is greater than the current instantaneous framerate, or perf gain if the fixed rate is less than the current framerate.

By default is unset and updates will use the current instantaneous framerate with 1 update and 1 draw each clock step.

publicreadonlygrabWindowFocus

grabWindowFocus: boolean

publicgraphicsContext

graphicsContext: ExcaliburGraphicsContext

Direct access to the ExcaliburGraphicsContext used for drawing things to the screen

publicinput

input: InputHost

Access engine input like pointer, keyboard, or gamepad

publicinputMapper

inputMapper: InputMapper

Map multiple input sources to specific game actions actions

publicmaxFps

maxFps: number = Number.POSITIVE_INFINITY

Optionally set the maximum fps if not set Excalibur will go as fast as the device allows.

You may want to constrain max fps if your game cannot maintain fps consistently, it can look and feel better to have a 30fps game than one that bounces between 30fps and 60fps

publicpageScrollPreventionMode

pageScrollPreventionMode: ScrollPreventionMode

The mouse wheel scroll prevention mode

publicpauseAudioWhenHidden

pauseAudioWhenHidden: boolean = true

Indicates whether audio should be paused when the game is no longer visible.

publicphysics

physics: Required<{ arcade?: Required<{ contactSolveBias?: ContactSolveBias }>; bodies?: Required<{ canSleepByDefault?: boolean; defaultMass?: number; sleepBias?: number; sleepEpsilon?: number; wakeThreshold?: number }>; colliders?: Required<{ compositeStrategy?: separate | together }>; continuous?: Required<{ checkForFastBodies?: boolean; disableMinimumSpeedForFastBody?: boolean; surfaceEpsilon?: number }>; dynamicTree?: Required<{ boundsPadding?: number; velocityMultiplier?: number }>; enabled?: boolean; gravity?: Vector; realistic?: Required<{ positionIterations?: number; slop?: number; steeringFactor?: number; velocityIterations?: number; warmStart?: boolean }>; solver?: SolverStrategy; sparseHashGrid?: SparseHashGridConfig; spatialPartition?: SpatialPartitionStrategy }>

Direct access to the physics configuration for excalibur

publicreadonlypointerScope

pointerScope: PointerScope

publicscreen

screen: Screen

Screen abstraction

publicreadonlyversion

version: string = EX_VERSION

Current Excalibur version string

Useful for plugins or other tools that need to know what features are available

staticContext

Context: Context<Engine<any>> = ...

staticInstanceCount

InstanceCount: number = 0

Accessors

publiccanvasHeight

  • get canvasHeight(): number
  • The height of the game canvas in pixels, (physical height component of the resolution of the canvas element)


    Returns number

publiccanvasWidth

  • get canvasWidth(): number
  • The width of the game canvas in pixels (physical width component of the resolution of the canvas element)


    Returns number

publiccurrentScene

  • get currentScene(): Scene<unknown>
  • The current [[Scene]] being drawn and updated on screen


    Returns Scene<unknown>

publiccurrentSceneName

  • get currentSceneName(): string
  • The current [[Scene]] being drawn and updated on screen


    Returns string

publicdisplayMode

  • Indicates the current [[DisplayMode]] of the engine.


    Returns DisplayMode

publicdrawHeight

  • get drawHeight(): number
  • Returns the height of the engine's visible drawing surface in pixels including zoom and device pixel ratio.


    Returns number

publicdrawWidth

  • get drawWidth(): number
  • Returns the width of the engine's visible drawing surface in pixels including zoom and device pixel ratio.


    Returns number

publichalfCanvasHeight

  • get halfCanvasHeight(): number
  • Returns half height of the game canvas in pixels (half physical height component)


    Returns number

publichalfCanvasWidth

  • get halfCanvasWidth(): number
  • Returns half width of the game canvas in pixels (half physical width component)


    Returns number

publichalfDrawHeight

  • get halfDrawHeight(): number
  • Returns half the height of the engine's visible drawing surface in pixels including zoom and device pixel ratio.


    Returns number

publichalfDrawWidth

  • get halfDrawWidth(): number
  • Returns half the width of the engine's visible drawing surface in pixels including zoom and device pixel ratio.


    Returns number

publicisDebug

  • get isDebug(): boolean
  • Returns boolean

publicisFullscreen

  • get isFullscreen(): boolean
  • Indicates whether the engine is set to fullscreen or not


    Returns boolean

publicisHiDpi

  • get isHiDpi(): boolean
  • Returns whether excalibur detects the current screen to be HiDPI


    Returns boolean

publicisInitialized

  • get isInitialized(): boolean
  • Gets whether the actor is Initialized


    Returns boolean

publicloadingComplete

  • get loadingComplete(): boolean
  • Returns true when loading is totally complete and the player has clicked start


    Returns boolean

publicpixelRatio

  • get pixelRatio(): number
  • Returns the calculated pixel ration for use in rendering


    Returns number

publicready

  • get ready(): boolean
  • Returns boolean

publicrootScene

  • get rootScene(): Scene<unknown>
  • The default [[Scene]] of the game, use [[Engine.goToScene]] to transition to different scenes.


    Returns Scene<unknown>

publicscenes

  • get scenes(): {}

publicsnapToPixel

  • get snapToPixel(): boolean
  • set snapToPixel(shouldSnapToPixel: boolean): void
  • Hints the graphics context to truncate fractional world space coordinates


    Returns boolean

  • Parameters

    • shouldSnapToPixel: boolean

    Returns void

publicstats

  • Access [[stats]] that holds frame statistics.


    Returns DebugStats

publictimescale

  • get timescale(): number
  • set timescale(value: number): void
  • Gets the current engine timescale factor (default is 1.0 which is 1:1 time)


    Returns number

  • Sets the current engine timescale factor. Useful for creating slow-motion effects or fast-forward effects when using time-based movement.


    Parameters

    • value: number

    Returns void

Methods

publicadd

  • Adds a [[Scene]] to the engine, think of scenes in Excalibur as you would levels or menus.


    Parameters

    Returns void

publicaddScene

  • Adds a [[Scene]] to the engine, think of scenes in Excalibur as you would levels or menus.


    Type parameters

    • TScene: string

    Parameters

    Returns Engine<TKnownScenes | TScene>

publicaddTimer

  • Adds a [[Timer]] to the [[currentScene]].


    Parameters

    • timer: Timer

      The timer to add to the [[currentScene]].

    Returns Timer

publicdispose

  • dispose(): void
  • Attempts to completely clean up excalibur resources, including removing the canvas from the dom.

    To start again you will need to new up an Engine.


    Returns void

publicemit

  • emit<TEventName>(eventName: TEventName, event: EngineEvents[TEventName]): void
  • emit(eventName: string, event?: any): void

publicgetAntialiasing

  • getAntialiasing(): boolean
  • Return the current smoothing status of the canvas

    @deprecated

    Set in engine constructor, will be removed in v0.30


    Returns boolean

publicgetWorldBounds

  • Returns a BoundingBox of the top left corner of the screen and the bottom right corner of the screen.


    Returns BoundingBox

publicgoToScene

  • goToScene<TData>(destinationScene: WithRoot<TKnownScenes>, options?: GoToOptions<TData>): Promise<void>
  • Changes the current scene with optionally supplied:

    • Activation data
    • Transitions
    • Loaders

    Example:

    game.goToScene('myScene', {
      sceneActivationData: {any: 'thing at all'},
      destinationIn: new FadeInOut({duration: 1000, direction: 'in'}),
      sourceOut: new FadeInOut({duration: 1000, direction: 'out'}),
      loader: MyLoader
    });

    Scenes are defined in the Engine constructor

    const engine = new ex.Engine({
       scenes: {...}
     });

    Or by adding dynamically

    engine.addScene('myScene', new ex.Scene());

    Type parameters

    • TData = undefined

    Parameters

    Returns Promise<void>

publicgoto

  • Changes the current scene with optionally supplied:

    • Activation data
    • Transitions
    • Loaders

    Example:

    game.goToScene('myScene', {
      sceneActivationData: {any: 'thing at all'},
      destinationIn: new FadeInOut({duration: 1000, direction: 'in'}),
      sourceOut: new FadeInOut({duration: 1000, direction: 'out'}),
      loader: MyLoader
    });

    Scenes are defined in the Engine constructor

    const engine = new ex.Engine({
       scenes: {...}
     });

    Or by adding dynamically

    engine.addScene('myScene', new ex.Scene());
    @deprecated

    use goToScene, it now behaves the same as goto


    Parameters

    Returns Promise<void>

publicisDisposed

  • isDisposed(): boolean
  • Returns boolean

publicisReady

  • isReady(): Promise<void>
  • Returns Promise<void>

publicisRunning

  • isRunning(): boolean
  • Returns the Engine's running status, Useful for checking whether engine is running or paused.


    Returns boolean

publicload

  • Another option available to you to load resources into the game. Immediately after calling this the game will pause and the loading screen will appear.


    Parameters

    • loader: DefaultLoader

      Some [[Loadable]] such as a [[Loader]] collection, [[Sound]], or [[Texture]].

    • hideLoader: boolean = false

    Returns Promise<void>

publicoff

  • off<TEventName>(eventName: TEventName, handler: Handler<EngineEvents[TEventName]>): void
  • off(eventName: string, handler: Handler<unknown>): void
  • off(eventName: string): void

publicon

publiconFatalException

  • onFatalException(e: any): void
  • The action to take when a fatal exception is thrown


    Parameters

    • e: any

    Returns void

publiconInitialize

  • onInitialize(engine: Engine<any>): void
  • Overridable implementation


    Parameters

    Returns void

publiconPostDraw

  • Overridable implementation


    Parameters

    Returns void

publiconPostUpdate

  • onPostUpdate(engine: Engine<any>, delta: number): void
  • Overridable implementation


    Parameters

    • engine: Engine<any>
    • delta: number

    Returns void

publiconPreDraw

  • Overridable implementation


    Parameters

    Returns void

publiconPreUpdate

  • onPreUpdate(engine: Engine<any>, delta: number): void
  • Overridable implementation


    Parameters

    • engine: Engine<any>
    • delta: number

    Returns void

publiconce

publicremove

  • Removes a scene instance from the engine


    Parameters

    Returns void

publicremoveScene

  • Removes a [[Scene]] instance from the engine


    Parameters

    Returns void

publicremoveTimer

  • Removes a [[Timer]] from the [[currentScene]].


    Parameters

    • timer: Timer

      The timer to remove to the [[currentScene]].

    Returns Timer

scope

  • scope<TReturn>(cb: () => TReturn): TReturn
  • Anything run under scope can use useEngine() to inject the current engine


    Type parameters

    • TReturn

    Parameters

    • cb: () => TReturn

    Returns TReturn

publicscreenToWorldCoordinates

  • Transforms the current x, y from screen coordinates to world coordinates


    Parameters

    • point: Vector

      Screen coordinate to convert

    Returns Vector

publicscreenshot

  • screenshot(preserveHiDPIResolution?: boolean): Promise<HTMLImageElement>
  • Takes a screen shot of the current viewport and returns it as an HTML Image Element.


    Parameters

    • preserveHiDPIResolution: boolean = false

      in the case of HiDPI return the full scaled backing image, by default false

    Returns Promise<HTMLImageElement>

publicsetAntialiasing

  • setAntialiasing(isSmooth: boolean): void
  • If supported by the browser, this will set the antialiasing flag on the canvas. Set this to false if you want a 'jagged' pixel art look to your image resources.

    @deprecated

    Set in engine constructor, will be removed in v0.30


    Parameters

    • isSmooth: boolean

      Set smoothing to true or false

    Returns void

publicshowDebug

  • showDebug(toggle: boolean): void
  • Enable or disable Excalibur debugging functionality.


    Parameters

    • toggle: boolean

      a value that debug drawing will be changed to

    Returns void

publicstart

  • Starts the internal game loop for Excalibur after loading any provided assets.


    Parameters

    • optionalloader: DefaultLoader

      Optional [[Loader]] to use to load resources. The default loader is [[Loader]], override to provide your own custom loader.

      Note: start() only resolves AFTER the user has clicked the play button

    Returns Promise<void>

publicstop

  • stop(): void
  • Stops Excalibur's main loop, useful for pausing the game.


    Returns void

publictoggleDebug

  • toggleDebug(): boolean
  • Toggle Excalibur debugging functionality.


    Returns boolean

publictoggleInputEnabled

  • toggleInputEnabled(enabled: boolean): void
  • Parameters

    • enabled: boolean

    Returns void

publicuseCanvas2DFallback

  • useCanvas2DFallback(): void
  • Switches the engine's graphics context to the 2D Canvas.

    @warning

    Some features of Excalibur will not work in this mode.


    Returns void

publicworldToScreenCoordinates

  • Transforms a world coordinate, to a screen coordinate


    Parameters

    • point: Vector

      World coordinate to convert

    Returns Vector

staticuseEngine