Game Classes

All top-level classes are namespaced under the global Whirl object. Therefore, any top-level class documented here is implied to be a property of the Whirl object unless specifically under a sub-header of another class.

All classes are initialised as you call them. You should not use the new keyword.


Whirl

The global Whirl object contains all the classes, constructors and constants that make up the Whirl game engine.

Whirl

Properties

Constructors

.Game()

Returns a new Game instance object.

.Sprite()

Returns a new Sprite instance object.

.Camera()

Returns a new Camera instance object.

.Text()

Returns a new advanced Text instance object.

.shapes

An object containing constructors for shapes for use in bounding boxes.

Functions

.util

An object containing various utility functions to assist in certain task.

.math

An object containing various mathematical functions and calculations.

.easing

An object containing functions for mathematical easing numerical values.

Constants

.STAGE

Used in Viewport instantiation to indicate the engine to automatically create a new Stage.

.CAMERA

Used in Viewport instantiation to indicate to the engine to automatically create a new Camera.


.Game()

Returns a new instance of a Game object.

The Game object is the actual running and workforce of the engine that updates your game, handles various object managers and deals with all interactions and rendering.

Whirl.Game(<config>)

Parameters

Object <config>

Preset configuration options for the Game instance.
Boolean ignoreWarnings - Ignore debug warnings (Default: true).
Object or Boolean input - Enable or disable certain input event listeners. If you have a very large amount of game objects and are not using certain input methods then disabling certain listeners may yield a slight performance boost.
Set to false to disable all inputs - useful if you just want to create some non-interactable animations or similar. Do not set or set to true to use the default input configuration (Listed below).
Boolean mouse - Whether mouse event listeners should be attached to the document and existing and subsequent viewports (Default: true).
Boolean keyboard - Whether keyboard event listeners should be attached to the document (Default: true).
Boolean preventDefault - Whether any events (mouse or keyboard) should have their default browser behaviour prevented (Default: false).
HTMLElement keyElement - Element that listens for keyboard input events (Implicitly uses game.input.setKeyElement) (Default: document.body).
HTMLElement mouseElement - Base element that listens for keyboard input events (Implicitly uses game.input.setMouseElement) (Default: document.body).
DO NOT set this to a canvas element that any viewports are applied to.

Any other properties given to the <config> object will be attached to the config object, too.

Examples(s):

Set all inputs to their defaults values.

const myGame = Whirl.Game();
// or
const myGame = Whirl.Game({
    input: true
});

myGame.config would then look like:

{
    "ignoreWarnings": true,
    "input": {
        "mouse": true,
        "keyboard": true,
        "preventDefault": false
    }
}

Turn off all inputs.

const myGame = Whirl.Game({
    input: false
});

myGame.config would then look like:

{
    "ignoreWarnings": true,
    "input": false
}

Turn off all mouse input, use an <input> element text box to listen for keyboard events and prevent the default mouse and keyboard behaviour.

// Get the input element
const myInput = document.querySelector("input#myInput");

const myGame =
Whirl.Game({
    input: {
        mouse: false,
        preventDefault: true,
        keyElement: myInput
    }
});

myGame.config would then look like:

{
    "ignoreWarnings": true,
    "input": {
        "mouse": false,
        "keyboard": true,
        "preventDefault": false,
        "keyElement": input#myInput
    }
}

Properties

.config

Object
Persistent configuration of the Game instance.
Also includes any additional properties given when initially creating a game instance.
.ignoreWarnings - Ignore debug warnings.
.input - See the input argument in the game instantiation parameters. After initialisation these properties should not be modified directly.

.frameRate (Read-only)

Integer
Limits the maximum frames per second (FPS).
Default 60.

.frameCount (Read-only)

Integer
The number of update frames elapsed since the game's start.
Will only start counting once the game has been started with the Game.start() method, not when the game is instantiated.

Methods

.setup(<options>)

Returns the Game object.

Object <options>

String canvas - Selector for an HTML5 <canvas> element.
String canvasWidth or cW - Width in pixels to resize the canvas element to.
String canvasHeight or cH - Height in pixels to resize the canvas element to.
If a canvas width or height value is not given then the canvas will not be resized.
Function setup - Called after the game has finished setting up (Called with the didSetup event).
Funtion update - Called when the game will update - before the update loop occurs each frame (Called with the willUpdate event).
Array assets - Array of assets to be loaded before the game is started. Implicitely calls the asset manager's .load method.

Automatically sets up the game with a Viewport, Stage and Camera.

This is not required to set up a game. Alternatively, a Viewport, Stage, Camera and assets can be set up manually. See the article "Advanced: Setting Up From Scratch".

Once setup has completed, the didSetup event is emitted on the game object and game loop is automatically started.

Example(s):

function gameSetup(data) {
    // Create objects, import assets, insert plugins, etc.
}

function gameLoop(data) {
    // Update object positions, detect key presses, animate sprites, etc.
}

const myGame = Whirl.Game()
    .setup({
        setup: gameSetup,
        update: gameLoop,

        canvas: "#myCanvas",
        canvasWidth: 400,
        canvasHeight: 400
    });

.start()

Returns the Game object.

  1. Sets the Game.running flag to true.
  2. Emits the willStart event.
  3. Starts the update and render loop.

By default the game does not start on creation, and must be started with this method.
Will not execute if the game is already running.

Example(s):

const myGame = Whirl.Game()
    .start();

.stop()

Returns the Game object.

  1. Sets the Game.running flag to false.
  2. Emits the willStop event.

This is a request to stop the game loop. It will not take effect immediately, but at the beginning of the next available check. Therefore, an extra update tick may run even after calling .stop().

Example(s):

const myGame = Whirl.Game()
    .start();

myGame.stop();

.Sprite()

Returns a new instance of a Sprite.Rectangle() object unless specified otherwise.

Sprites are visible "things" in your game world. They have a position, bounding box, a fill colour or image and a plethora of other properties that can be modified.

All Sprites inherit from a Whirl.Sprite._baseSprite class and different types of Sprites extend the functionality of the base Sprite.

Inherits the tween object system.

Whirl.Sprite(<Game>, <name>, <fill>, <options>)

By just calling Whirl.Sprite() it will return a Rectangle Sprite. Different types of sprites can be instantiated by adding .<Sprite Type>(...).

The following Sprite types are available: Whirl.Sprite.Rectangle(...) and Whirl.Sprite.Circle(...).

Parameters

Object <Game>

An already instantiated Game object.

All sprites must be instantiated into an existing game instance so that they can be handled by the global object manager.

String <name>

A custom name for the Sprite.

This name is used for identification as well as better indexing capabilities and searching the global object store.

String or Object or NULL <fill>

A colour or image to fill the Sprite with.
Performs the same function as the .setFill(...) method.

Providing a string will attempt to resolve the fill to a colour.
Do not give colour values with transparency. Instead use the .alpha property.
Example(s): rgb(0, 255, 220) or #F00 or cyan etc.

If an object is given, it must be a Whirl.Asset image object.
Most Sprite types will attempt to scale the image to their bounds.

If null or any other non-valid fill value is given then the Sprite will be given a transparent colour fill by default.

Object <options>

String outline - String colour value for a one-pixel thick outline of the Sprite (Default: false).
Float alpha - Alpha/transparency for the Sprite (0 to 1) (Default: 1).
Float scale - The scale of this Sprite - scales its bounding box size (Default: 1).
Integer z - The z-index (Layer) of this Sprite (Default: 0).

Properties

.name

String
The name of the Sprite.

Used by the global object manager to search for Sprites.

._fill (Read-only)

Object
Do not modify directly. Use the .setFill() method.
Information about the Sprite's fill.
.type - Type of fill. Can either be "colour" or "image".
.data - Data of the fill. The colour value or the image asset.

.outline

String
If not set to a falsey value, a one-pixel thick line of the given colour value will be drawn around the sprite.
Not affected by the .alpha property.
Typically used for debugging.

.alpha

Float
Adjusts the alpha/transparency for the Sprite.
Must only be between 0 and 1.
An alpha of 1 means the sprite is visible as normal. An alpha of 0 means the sprite is completely invisible.

.scale

Float
Scales the Sprite's bounds by the given value.
By default all Sprites scale from their top-left origin point, however this can be changed if the Sprite offers an anchor property.

.z

Integer
The z-axis value for this Sprite. Allows for 'layering' of Sprites over one-another.
A Sprite with a z value higher than another's will appear ontop of the other.
Sprites with the same z value will be ordered by their initial order in the object store.

Methods

.setFill(<fill>)

See the Sprite <fill> parameter.
Returns the Sprite object.

Example(s):

mySprite.setFill("rgb(100, 255, 255)");

mySprite.setFill("#F00");

mySprite.setFill("blue");

.tween.

See the tween object system.


.Rectangle()

Returns a new instance of a rectangle Sprite object.

Extends and inherits the base sprite parameters, properties and methods.

Rectangle sprite bounds are defined by a top-left point and a width and height.

Whirl.Sprite(<Game>, <name>, <fill>, <options>)
// or
Whirl.Sprite.Rectangle(<Game>, <name>, <fill>, <options>)

Parameters

Object <options>

Number x - X-coordinate of the bounding box (Default: 0).
Number y - Y-coordinate of the bounding box (Default: 0).
Number w - Width of the bounding box (Default: 0).
Number h - Height of the bounding box (Default: 0).
Object anchor - Moves the anchor/origin point: Float x - X-coordinate of the anchor point (Default: 0).
Float y - X-coordinate of the anchor point (Default: 0).

Properties

.bounds

Object
The bounding position and dimensions of this sprite.
Derived from Whirl.shapes.Rectangle(...).
.x - X-coordinate of the bounding box.
.y - Y-coordinate of the bounding box.
.w - Width of the bounding box.
.h - Height of the bounding box.

.anchor

Object
Sets the anchor / origin point of the sprite's coordinates.
.x - X-coordinate of the origin point.
.y - Y-coordinate of the origin point.

By default the x and y origin point are located at (0, 0), the top-left point of the sprite.
(1, 1) would be the bottom-right and (0.5, 0.5) would be the very center.

Methods

.resizeToImage(<scale>)

Will not execute if the Sprite does not have an image fill type.
Automatically sets the bounding box's width and height to the same dimensions as the image's width and height.
Returns the Sprite object.

Float <scale>

Scales the width and height value of the Sprite after modifying it (Default: 1).

.anchor.center()

Sets the anchor point to (0.5, 0.5).
Returns the Sprite object.


.Circle()

Returns a new instance of a circle Sprite object.

Extends and inherits the base sprite parameters, properties and methods.

Circle sprites bounds are defined by a center point and a radius.

Whirl.Sprite.Circle(<Game>, <name>, <fill>, <options>)

Parameters

Object <options>

Number x - X-coordinate of the center point (Default: 0).
Number y - Y-coordinate of the center point (Default: 0).
Number r - Radius of the circle (Default: 0).

Properties

.bounds

Object
The bounding position and dimensions of this Sprite.
Derived from Whirl.shapes.Circle(...).
.x - X-coordinate of the bounding box.
.y - Y-coordinate of the bounding box.
.r - Radius of the circle.


.Camera()

Returns a new instance of a Camera object.

Cameras serve as the view into your world (the Stage). Scrolling the camera around lets you look around different parts of your world. Cameras can be scrolled around, lock onto objects, zoom in/out, apply effects and more.

Inherits the tween object system.

Whirl.Camera(<Game>, <options>)

Parameters

Object <Game>

An already instantiated Game object.

Object <options>

Number .x - X-coordinate of the bounding box (Default: 0).
Number .y - Y-coordinate of the bounding box (Default: 0).
Number .w - Width of the camera view (Default: 0).
Number .h - Height of the camera view (Default: 0).
Object anchor - Moves the anchor/origin point: Float x - X-coordinate of the anchor point (Default: 0).
Float y - Y-coordinate of the anchor point (Default: 0).
Object scroll - Scrolls the Camera view around the game world: Float x - X-coordinate of the scroll position (Default: 0).
Float y - Y-coordinate of the scroll position (Default: 0).
Float zoom - Zoom level of the Camera (Default: 1).
Boolean roundPixels - Whether to round the scroll position to the nearest whole number (Default true).

Properties

.bounds

Object
The position and dimensions of the Camera on screen.
Derived from Whirl.shapes.Rectangle(...).
.x - X-coordinate of the bounding box.
.y - Y-coordinate of the bounding box.
.w - Width of the bounding box.
.h - Height of the bounding box.
Note that the .bounds property defines where the Camera will draw to on the screen, not where it will draw from in the world.
Use the .scroll property to move around in space.
The width and height properties do not cut off rendering on the screen, but are used to determine render culling zones and no-update zones.

.anchor

Object
Sets the anchor / origin point of the camera's coordinates and zoom.
.x - X-coordinate of the origin point.
.y - Y-coordinate of the origin point.
Has no effect if the Camera is following an object.

._followObject (Read-only)

Object
Do not modify directly. Use the .follow(...) and .unfollow() methods.
Reference to the object that the Camera is following.

.scroll

Object
The position in the world that the Camera is observing. Moves the camera's view around the game world.
.x - X-coordinate of the scroll position.
.y - Y-coordinate of the scroll position.
Changing this will have no effect if the Camera is following an object (._followObject) as its scroll position is bound to the object it is following.

.zoom

Number
The zoom of the camera. Scales what the camera sees up/down by the given amount. Will always zoom around the anchor point.
A zoom level of 1 (Default) means no scaling / a normal view.
A zoom level of 2 would zoom in twice the normal amount - you would see half of normal view.
A zoom level of .5 would zoom out twice the normal amount - you would see double the amount of the normal view.

.roundPixels

Rounds the scroll (.scroll) position to the nearest whole number if the Camera is locked to an object.

Methods

.follow(<Sprite>, <lerp>)

Makes the camera follow the given Sprite by "locking" the camera's center point to the Sprite position.
Returns the Camera object.

Object <Sprite> Sprite object that the Camera should follow.

Float <lerp> (Optional) (Default: 1) Implicitely calls .setLerp with the given <lerp> value.

When a Camera follows a Sprite it will attempt to keep the Sprite in the exact center of the screen each update, moving the scroll (.scroll) position to the center of the Sprite's bounds by the linear interpolation value.
Invokes the .anchor.center() method to center the Camera on the Sprite.

Example(s):

const mySprite = Whirl.Sprite(myGame, "Blocky", "#F00", {
    x: 100,
    y: 75,
    w: 50,
    h: 50
});

const myCamera = Whirl.Camera(myGame, {
    w: 400,
    h: 400
})
    .follow(mySprite);

.unfollow()

Stops the camera following any object it is currently following (._followObject).
Returns the Camera object.

When "unlocked", the scroll (.scroll) will stay in its last position that it was locked at, essentially not moving.

The zoom (.zoom) and anchor (.anchor) positions remain unchanged throughout the time that the Camera is locked, so will still be the same after unlocking.

Example(s):

myCamera.unfollow();

.setLerp(<lerp>)

Sets the linear interpolation that the camera uses to follow the Sprite.
Has no effect if the Camera is not following an object (._followObject).
Returns the Camera object.

Float <lerp> Linear interpolation value to use.
Value between 0 and 1. 1 means the Camera is locked to the object, anything below will make the Camera move slower to catch up to the Sprite.

Example(s):

myCamera.setLerp(1);

myCamera.setLerp(.6);

myCamera.setLerp(.1);

.centerOn(<Sprite>)

Moves the Camera's scroll position so that the Camera is centered on the given Sprite.
Returns the Camera object.

Object <Sprite> Sprite object that Camera centers on.

Example(s):

myCamera.centerOn(mySprite);

.anchor.center()

Sets the anchor point to (0.5, 0.5).
Returns the Camera object.

.tween.

See the tween object system.


Stage

A stage is the 'world' of your game that you put your game objects into. It used for keeping track of and updating game objects in the world.

Objects not contained in a Stage are not rendered or updated.

Stages and their contents are rendered using a Viewport and will update by themselves even when not being rendered.

Inherits the child object system.

<Game>.stageManager.add(<name>, <options>)

<Game> represents an already instantiated game instance.

The above code would return a reference to the Stage object as contained in the Stage Manager.

Parameters

String <name>

A custom name for the Stage.

This name is used for identification and is searched and indexed by the Stage Manager.

Object <options>

Number .x - X-coordinate of the stage limits (Default: 0).
Number .y - Y-coordinate of the stage limits (Default: 0).
Number .w - Width of the stage limits (Default: 0).
Number .y - Height of the stage limits (Default: 0).

Properties

.name

String
The name of the Stage.

Used by the stage and global object manager to search for Stages.

.limits

Object
The limits of the game world.
Objects with physics applied cannot leave the limits of the game world.
Derived from Whirl.shapes.Rectangle(...).
.x - X-coordinate of the stage limits.
.y - Y-coordinate of the stage limits.
.w - Width of the stage limits.
.h - Height of the stage limits.

Methods

.child.

See the child object system.

Objects must be contained inside a Stage using the child object system.
Only objects that are children of a Stage are updated and/or rendered.


Viewport

A viewport is a screen that renders to an HTML5 Canvas.

Viewports hold the render settings used by the canvas element and require a Stage and Camera to use for rendering.

<Game>.viewportManager.add(<name>, <canvas>, <Stage>, <Camera>, <options>)

<Game> represents an already instantiated game instance.

The above code would return a reference to the Viewport object as contained in the Viewport Manager.

Parameters

String <name>

A custom name for the Viewport.

This name is used for identification and is searched and indexed by the Viewport Manager.

String <canvas>

Selector for a <canvas> element contained in the DOM.
Performs the same function as the .setCanvas(...) method.

Object or String <Stage>

An already instantiated Stage object.
Performs the same function as the .setStage(...) method.

Alternatively, Whirl.STAGE can be given and a new Stage object will be automatically created and associated with the Viewport.

Object or String <Camera>

An already instantiated Camera object.
Performs the same function as the .setCamera(...) method.

Alternatively, Whirl.CAMERA can be given and a new Camera object with the same dimensions will be automatically created and associated with the Viewport.

Object <options>

Number x - X-coordinate of the bounding box (Default: 0).
Number y - Y-coordinate of the bounding box (Default: 0).
Number w - Width of the bounding box (Default: 0).
Number h - Height of the bounding box (Default: 0).
Integer cW - Resize the <canvas> element to a given width.
Integer cH - Resize the <canvas> element to a given height.
Boolean imageSmoothing - Canvas anti-aliasing enabled or not (Default: true).
Boolean clear - Clear canvas at the beginning of each render loop (Default: true).
Boolean clip - Clip out anything rendered beyond the Viewport's boundaries (Default: true).
Boolean fitCamera - Resize and move the Camera to the same coordinates and dimensions as the Viewport (Default: true).

Properties

.name

String
The name of the Viewport.

Used by the viewport and global object manager to search for Viewports.

.bounds

Object
The bounding position and dimensions of this viewport on the screen.
Derived from Whirl.shapes.Rectangle(...).
.x - X-coordinate of the bounding box.
.y - Y-coordinate of the bounding box.
.w - Width of the bounding box.
.h - Height of the bounding box.
Viewports should be static. Object clipping and screen clearing is based on the .bounds property and therefore it should not be modified after the initial definition in the <options> parameter.

.c (Read-only)

Object
Do not modify directly. Use the .setCanvas(...) method.
Reference to the HTML5 canvas element that the viewport will render to.
This holds the actual element node, not just a selector or a copy.

.ctx (Read-only)

Object
Do not modify directly. Use the .setCanvas(...) method.
Reference to the drawing context of the viewport's canvas.

.activeStage (Read-only)

Object
Do not modify directly. Use the .setStage(...) method.
Reference to the Stage being rendered.

.activeCamera (Read-only)

Object
Do not modify directly. Use the .setCamera(...) method.
Reference to the Camera being used for rendering.

.imageSmoothing

Boolean
Whether scaled images are smoothed (anti-aliased) or not.
Useful for games that use pixel art a lot.

.clear

Boolean
Clear the canvas at the beginning of every render loop.
Only the area that the viewport occupies on the canvas is cleared. If the viewport has the same dimensions as the canvas then the entire canvas will be cleared.

.clip

Boolean
Clip out anything in the entire canvas that is not within the viewport's boundaries.
It is recommended to disable this if there is more than one viewport being used on the same canvas.

Methods

.setCanvas(<canvas>)

Sets the HTML5 canvas element to render to.
Also see the .c and .ctx viewport properties.
Returns the Viewport object.

String <canvas> Selector string for an HTML5 <canvas> element.

Example(s):

myViewport.setCanvas("#myCanvas");

.setStage(<Stage>)

Sets the current stage to be rendered.
Also see the .activeStage viewport property.
Returns the Viewport object.

Object <Stage> An already instantiated Stage object.

The Whirl.STAGE constant can be given instead and a new Stage object will be automatically created with the same position and dimensions as the viewport.

.setCamera(<Camera>)

Sets the current camera to be used for rendering.
Also see the .activeCamera viewport property.
Returns the Viewport object.

Object <Camera> An already instantiated Camera object.

The Whirl.CAMERA constant can be given instead and a new Camera object will be automatically created with the same position and dimensions as the viewport.

If the fitCamera viewport parameter is not explicitly set to the false then the given camera will be repositioned and resized to the same position and dimensions of the viewport.

.bringCamera()

Returns the Viewport object.

Moves the active camera's scroll position to the top-left point of the viewport's position.

If the viewport is placed anywhere that isnt (0, 0) it is recommended to bring the camera to avoid discrepancies between rendering zones and unwanted clipping of objects by the viewport after they have been rendered.

Example(s):

const myCamera = Whirl.Camera(myGame, {
    x: 50,
    y: 75,
    w: 200,
    h: 200
});

const myViewport = myGame.viewportManager.add(..., ..., ..., myCamera, {
    x: 0,
    y: 0,
    w: 400,
    h: 400
})
    .bringCamera();

// The camera is now moved from (50, 75) and 200 width and height to (0, 0) and 400 width and height.