Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Engine

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.

Excalibur uses the HTML5 Canvas API for drawing your game to the screen. The canvas is available to all draw functions for raw manipulation, but Excalibur is meant to simplify or completely remove the need to use the canvas directly.

Creating a Game

To create a new game, create a new instance of Engine and pass in the configuration (EngineOptions). Excalibur only supports a single instance of a game at a time, so it is safe to use globally. You can then call start which starts the game and optionally accepts a Loader which you can use to pre-load assets.

var game = new ex.Engine({
  width: 800, // the width of the canvas
  height: 600, // the height of the canvas
  canvasElementId: '', // the DOM canvas element ID, if you are providing your own
  displayMode: ex.DisplayMode.FullScreen, // the display mode
  pointerScope: ex.Input.PointerScope.Document // the scope of capturing pointer (mouse/touch) events
});
// call game.start, which is a Promise
game.start().then(function() {
  // ready, set, go!
});

The Main Loop

The Excalibur engine uses a simple main loop. The engine updates and renders the "scene graph" which is the scenes and the tree of actors within that scene. Only one Scene can be active at a time. The engine does not update/draw any other scene, which means any actors will not be updated/drawn if they are part of a deactivated scene. Engine Lifecycle

Scene Graph

Engine
  |_ Scene 1 (activated)
    |_ Actor 1
      |_ Child Actor 1
    |_ Actor 2
  |_ Scene 2 (deactivated)
  |_ Scene 3 (deactivated)

The engine splits the game into two primary responsibilities: updating and drawing. This is to keep your game smart about splitting duties so that you aren't drawing when doing logic or performing logic as you draw.

Update Loop

The first operation run is the Update loop. Actor and Scene both implement an overridable/extendable update method. Use it to perform any logic-based operations in your game for a particular class.

Draw Loop

The next step is the Draw loop. A Scene loops through its child actors and draws each one. You can override the draw method on an actor to customize its drawing. You should not perform any logic in a draw call, it should only relate to drawing.

Working with Scenes

The engine automatically creates a "root" Scene. You can use this for whatever you want. You can manipulate scenes using add, remove, and goToScene. You can overwrite or remove the root scene if you want. There always has to be at least one scene and only one scene can be active at any one time.

Learn more about the scene lifecycle.

Adding a scene

var game = new ex.Engine();
// create a new level
var level1 = new ex.Scene();
// add level 1 to the game
game.add('level1', level1);
// in response to user input, go to level 1
game.goToScene('level1');
// go back to main menu
game.goToScene('root');

Accessing the current scene

To add actors and other entities to the current Scene, you can use add. Alternatively, you can use Engine.currentScene to directly access the current scene.

Managing the Viewport

Excalibur supports multiple display modes for a game. Pass in a displayMode option when creating a game to customize the viewport.
The canvasWidth and canvasHeight are still used to represent the native width and height of the canvas, but you can leave them at 0 or undefined to ignore them. If width and height are not specified, the game won't be scaled and native resolution will be the physical screen width/height.

If you use DisplayMode.Container, the canvas will automatically resize to fit inside of it's parent DOM element. This allows you maximum control over the game viewport, e.g. in case you want to provide HTML UI on top or as part of your game.

You can use DisplayMode.Position to specify where the game window will be displayed on screen. if this DisplayMode is selected, then a position option must be provided to the Engine constructor. The position option can be a String or an IAbsolutePosition. The first word in a String must be the desired vertical alignment of the window. The second (optional) word is the desired horizontal alignment.

Valid String examples: "top left", "top", "bottom", "middle", "middle center", "bottom right" Valid IAbsolutePosition examples: {top: 5, right: 10%}, {bottom: 49em, left: 10px}, {left: 10, bottom: 40}

Extending the Engine

For complex games, any entity that inherits Class can be extended to override built-in functionality. This is recommended for actors and scenes, especially. You can customize the options or provide more for your game by extending Engine.

TypeScript

class Game extends ex.Engine {
  constructor() {
    super({ width: 800, height: 600, displayMode: DisplayMode.FullScreen });
  }

  public start() {
    // add custom scenes
    this.add('mainmenu', new MainMenu());
    return super.start(myLoader).then(() => {
      this.goToScene('mainmenu');
      // custom start-up
    });
  }
}
var game = new Game();
game.start();

Javascript

var Game = ex.Engine.extend({

  constructor: function () {
    Engine.call(this, { width: 800, height: 600, displayMode: DisplayMode.FullScreen });
  }

  start: function() {
    // add custom scenes
    this.add("mainmenu", new MainMenu());
    var _this = this;
    return Engine.prototype.start.call(this, myLoader).then(function() {
      _this.goToScene("mainmenu");
      // custom start-up
    });
  }
});
var game = new Game();
game.start();

Hierarchy

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.Input.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!
    });

    Parameters

    Returns Engine

Properties

backgroundColor

backgroundColor: Color

Sets the background color for the engine.

browser

browser: BrowserEvents

canvas

canvas: HTMLCanvasElement

Direct access to the engine's canvas element

canvasElementId

canvasElementId: string

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

ctx

ctx: CanvasRenderingContext2D

Direct access to the engine's 2D rendering context

currentScene

currentScene: Scene

The current Scene being drawn and updated on screen

debug

debug: Debug = new Debug()

Access Excalibur debugging functionality.

debugColor

debugColor: Color = new Color(255, 255, 255)

displayMode

displayMode: DisplayMode = DisplayMode.FullScreen

Indicates the current DisplayMode of the engine.

enableCanvasTransparency

enableCanvasTransparency: boolean = true

Sets the Transparency for the engine.

eventDispatcher

eventDispatcher: EventDispatcher

Direct access to the game object event dispatcher.

input

Access engine input like pointer, keyboard, or gamepad

isDebug

isDebug: boolean = false

Indicates whether the engine should draw with debug information

isFullscreen

isFullscreen: boolean = false

Indicates whether the engine is set to fullscreen or not

pageScrollPreventionMode

pageScrollPreventionMode: ScrollPreventionMode

The mouse wheel scroll prevention mode

pauseAudioWhenHidden

pauseAudioWhenHidden: boolean = true

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

position

position: string | AbsolutePosition

Indicates the current position of the engine. Valid only when DisplayMode is DisplayMode.Position

postProcessors

postProcessors: PostProcessor[] = []

Gets or sets the list of post processors to apply at the end of drawing a frame (such as ColorBlindCorrector)

rootScene

rootScene: Scene

The default Scene of the game, use Engine.goToScene to transition to different scenes.

scenes

scenes: object

Contains all the scenes currently registered with Excalibur

Type declaration

Accessors

canvasHeight

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

    Returns number

canvasWidth

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

    Returns number

drawHeight

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

    Returns number

drawWidth

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

    Returns number

halfCanvasHeight

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

    Returns number

halfCanvasWidth

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

    Returns number

halfDrawHeight

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

    Returns number

halfDrawWidth

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

    Returns number

isHiDpi

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

    Returns boolean

isInitialized

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

    Returns boolean

pixelRatio

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

    Returns number

stats

timescale

  • 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

Protected _addChild

  • _addChild(actor: Actor): void
  • Adds an actor to the currentScene of the game. This is synonymous to calling engine.currentScene.add(actor).

    Actors can only be drawn if they are a member of a scene, and only the currentScene may be drawn or updated.

    Parameters

    Returns void

_postdraw

  • _postdraw(_ctx: CanvasRenderingContext2D, delta: number): void
  • internal

    Parameters

    • _ctx: CanvasRenderingContext2D
    • delta: number

    Returns void

_postupdate

  • _postupdate(delta: number): void
  • internal

    Parameters

    • delta: number

    Returns void

_predraw

  • _predraw(_ctx: CanvasRenderingContext2D, delta: number): void
  • internal

    Parameters

    • _ctx: CanvasRenderingContext2D
    • delta: number

    Returns void

_preupdate

  • _preupdate(delta: number): void
  • internal

    Parameters

    • delta: number

    Returns void

Protected _removeChild

  • _removeChild(actor: Actor): void
  • Removes an actor from the currentScene of the game. This is synonymous to calling engine.currentScene.remove(actor). Actors that are removed from a scene will no longer be drawn or updated.

    Parameters

    Returns void

add

  • add(sceneKey: string, scene: Scene): void
  • add(timer: Timer): void
  • add(tileMap: TileMap): void
  • add(actor: Actor): void
  • add(uiActor: UIActor): void
  • Adds a Scene to the engine, think of scenes in Excalibur as you would levels or menus.

    Parameters

    • sceneKey: string

      The key of the scene, must be unique

    • scene: Scene

      The scene to add to the engine

    Returns void

  • Adds a Timer to the currentScene.

    Parameters

    Returns void

  • Adds a TileMap to the currentScene, once this is done the TileMap will be drawn and updated.

    Parameters

    Returns void

  • Adds an actor to the currentScene of the game. This is synonymous to calling engine.currentScene.add(actor).

    Actors can only be drawn if they are a member of a scene, and only the currentScene may be drawn or updated.

    Parameters

    Returns void

  • Adds a UIActor to the currentScene of the game, UIActors do not participate in collisions, instead the remain in the same place on the screen.

    Parameters

    Returns void

addScene

  • addScene(key: string, scene: Scene): void
  • Adds a Scene to the engine, think of scenes in Excalibur as you would levels or menus.

    Parameters

    • key: string

      The name of the scene, must be unique

    • scene: Scene

      The scene to add to the engine

    Returns void

addTileMap

  • addTileMap(tileMap: TileMap): void

addTimer

emit

  • emit(eventName: string, eventObject: GameEvent<any>): void
  • Emits a new event

    Parameters

    • eventName: string

      Name of the event to emit

    • eventObject: GameEvent<any>

      Data associated with this event

    Returns void

getAntialiasing

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

    Returns boolean

getWorldBounds

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

    Returns BoundingBox

goToScene

  • goToScene(key: string): void
  • Changes the currently updating and drawing scene to a different, named scene. Calls the Scene lifecycle events.

    Parameters

    • key: string

      The key of the scene to transition to.

    Returns void

isPaused

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

    Returns boolean

load

  • 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

    Returns Promise<any>

off

  • off(eventName: Events.initialize, handler?: function): void
  • off(eventName: Events.visible, handler?: function): void
  • off(eventName: Events.hidden, handler?: function): void
  • off(eventName: Events.start, handler?: function): void
  • off(eventName: Events.stop, handler?: function): void
  • off(eventName: Events.preupdate, handler?: function): void
  • off(eventName: Events.postupdate, handler?: function): void
  • off(eventName: Events.preframe, handler?: function): void
  • off(eventName: Events.postframe, handler?: function): void
  • off(eventName: Events.predraw, handler?: function): void
  • off(eventName: Events.postdraw, handler?: function): void
  • off(eventName: string, handler?: function): void

on

  • on(eventName: Events.initialize, handler: function): void
  • on(eventName: Events.visible, handler: function): void
  • on(eventName: Events.hidden, handler: function): void
  • on(eventName: Events.start, handler: function): void
  • on(eventName: Events.stop, handler: function): void
  • on(eventName: Events.preupdate, handler: function): void
  • on(eventName: Events.postupdate, handler: function): void
  • on(eventName: Events.preframe, handler: function): void
  • on(eventName: Events.postframe, handler: function): void
  • on(eventName: Events.predraw, handler: function): void
  • on(eventName: Events.postdraw, handler: function): void
  • on(eventName: string, handler: function): void

onFatalException

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

    Parameters

    • e: any

    Returns void

onInitialize

  • onInitialize(_engine: Engine): void

onPostDraw

  • onPostDraw(_ctx: CanvasRenderingContext2D, _delta: number): void

onPostUpdate

  • onPostUpdate(_engine: Engine, _delta: number): void

onPreDraw

  • onPreDraw(_ctx: CanvasRenderingContext2D, _delta: number): void

onPreUpdate

  • onPreUpdate(_engine: Engine, _delta: number): void

once

  • once(eventName: Events.initialize, handler: function): void
  • once(eventName: Events.visible, handler: function): void
  • once(eventName: Events.hidden, handler: function): void
  • once(eventName: Events.start, handler: function): void
  • once(eventName: Events.stop, handler: function): void
  • once(eventName: Events.preupdate, handler: function): void
  • once(eventName: Events.postupdate, handler: function): void
  • once(eventName: Events.preframe, handler: function): void
  • once(eventName: Events.postframe, handler: function): void
  • once(eventName: Events.predraw, handler: function): void
  • once(eventName: Events.postdraw, handler: function): void
  • once(eventName: string, handler: function): void

playAnimation

  • playAnimation(animation: Animation, x: number, y: number): void
  • Plays a sprite animation on the screen at the specified x and y (in game coordinates, not screen pixels). These animations play independent of actors, and will be cleaned up internally as soon as they are complete. Note animations that loop will never be cleaned up.

    Parameters

    • animation: Animation

      Animation to play

    • x: number

      x game coordinate to play the animation

    • y: number

      y game coordinate to play the animation

    Returns void

remove

  • remove(scene: Scene): void
  • remove(sceneKey: string): void
  • remove(timer: Timer): void
  • remove(tileMap: TileMap): void
  • remove(actor: Actor): void
  • remove(uiActor: UIActor): void
  • Removes a scene instance from the engine

    Parameters

    • scene: Scene

      The scene to remove

    Returns void

  • Removes a scene from the engine by key

    Parameters

    • sceneKey: string

      The scene to remove

    Returns void

  • Removes a Timer from the currentScene.

    Parameters

    Returns void

  • Removes a TileMap from the currentScene, it will no longer be drawn or updated.

    Parameters

    Returns void

  • Removes an actor from the currentScene of the game. This is synonymous to calling engine.currentScene.removeChild(actor). Actors that are removed from a scene will no longer be drawn or updated.

    Parameters

    Returns void

  • Removes a UIActor to the scene, it will no longer be drawn or updated

    Parameters

    Returns void

removeScene

  • removeScene(scene: Scene): void
  • removeScene(key: string): void
  • Removes a Scene instance from the engine

    Parameters

    • scene: Scene

      The scene to remove

    Returns void

  • Removes a scene from the engine by key

    Parameters

    • key: string

      The scene key to remove

    Returns void

removeTileMap

  • removeTileMap(tileMap: TileMap): void

removeTimer

screenToWorldCoordinates

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

    Parameters

    • point: Vector

      Screen coordinate to convert

    Returns Vector

screenshot

  • screenshot(): HTMLImageElement
  • Takes a screen shot of the current viewport and returns it as an HTML Image Element.

    Returns HTMLImageElement

setAntialiasing

  • 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.

    Parameters

    • isSmooth: boolean

      Set smoothing to true or false

    Returns void

start

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

    Parameters

    • Optional loader: CanLoad

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

    Returns Promise<any>

stop

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

    Returns void

worldToScreenCoordinates

  • Transforms a world coordinate, to a screen coordinate

    Parameters

    • point: Vector

      World coordinate to convert

    Returns Vector

Static createMainLoop

  • createMainLoop(game: Engine, raf: function, nowFn: function): mainloop
  • Parameters

    • game: Engine
    • raf: function
        • (func: Function): number
        • Parameters

          • func: Function

          Returns number

    • nowFn: function
        • (): number
        • Returns number

    Returns mainloop

Static extend

  • extend(methods: any): any
  • You may wish to extend native Excalibur functionality in vanilla Javascript. Any method on a class inheriting Class may be extended to support additional functionality. In the example below we create a new type called MyActor.

    var MyActor = Actor.extend({
    
       constructor: function() {
          this.newprop = 'something';
          Actor.apply(this, arguments);
       },
    
       update: function(engine, delta) {
          // Implement custom update
          // Call super constructor update
          Actor.prototype.update.call(this, engine, delta);
    
          console.log("Something cool!");
       }
    });
    
    var myActor = new MyActor(100, 100, 100, 100, Color.Azure);

    In TypeScript, you only need to use the extends syntax, you do not need to use this method of extension.

    Parameters

    • methods: any

      A JSON object contain any methods/properties you want to extend

    Returns any