Shaku

Shaku JS

Back To Table of Content

Shaku

Classes

Asset

A loadable asset base class. All asset types inherit from this.

Assets

Assets manager class. Used to create, load and cache game assets, which includes textures, audio files, JSON objects, etc. As a rule of thumb, all methods to load or create assets are async and return a promise.

To access the Assets manager you use Shaku.assets.

BinaryAsset

A loadable binary data asset. This asset type loads array of bytes from a remote file.

FontTextureAsset

A font texture asset, dynamically generated from loaded font and canvas. This asset type creates an atlas of all the font's characters as textures, so we can later render them as sprites.

JsonAsset

A loadable json asset. This asset type loads JSON from a remote file.

MsdfFontTextureAsset

A MSDF font texture asset, from a pregenerated msdf texture atlas (from msdf-bmfont-xml, for example). This asset uses a signed distance field atlas to render characters as sprites at high res.

SoundAsset

A loadable sound asset. This is the asset type you use to play sounds.

TextureAsset

A loadable texture asset. This asset type loads an image from URL or source, and turn it into a texture.

TextureAssetBase

Base type for all texture asset types.

TextureAtlasAsset

A texture atlas we can build at runtime to combine together multiple textures.

TextureInAtlasAsset

A texture that is part of a texture atlas. Stores a texture that was generated by the texture atlas + the source rectangle in texture for this segment.

Collision

Collision is the collision manager. It provides basic 2d collision detection functionality. Note: this is not a physics engine, its only for detection and objects picking.

To access the Collision manager you use Shaku.collision.

CollisionWorld

A collision world is a set of collision shapes that interact with each other. You can use different collision worlds to represent different levels or different parts of your game world.

CollisionResolver

The collision resolver is responsible to implement collision detection between pair of shapes of same or different types.

CollisionTestResult

Collision detection result.

CircleShape

Collision circle class.

LinesShape

Collision lines class. This shape is made of one line or more.

PointShape

Collision point class.

RectangleShape

Collision rectangle class.

CollisionShape

Collision shape base class.

TilemapShape

Collision tilemap class. A collision tilemap shape is a grid of equal-sized cells that can either block or not (+ have collision flags). Its the most efficient (both memory and CPU) way to implement grid based / tilemap collision.

Camera

Implements a Camera object.

Camera3D

Implements a 3d Camera object.

DrawBatch

Base class for a drawing batch, used to draw a collection of sprites or shapes.

LinesBatch

Colored lines renderer. Responsible to drawing a batch of line segments or strips.

ShapesBatch

Colored shapes renderer. Responsible to drawing a batch of basic geometric shapes with as little draw calls as possible.

SpriteBatch

Sprite batch renderer. Responsible to drawing a batch of sprites with as little draw calls as possible.

SpriteBatch3D

3D Sprites batch renderer. Responsible to drawing 3D quads with textures on them.

SpriteBatchBase

Base class for sprite-based rendering, ie vertices with textures.

TextSpriteBatch

Text sprite batch renderer. Responsible to drawing a batch of characters sprites.

Effect

Effect base class. An effect = vertex shader + fragment shader + uniforms & attributes + setup code.

MsdfFontEffect

Default effect to draw MSDF font textures.

ShapesEffect

Default basic effect to draw 2d shapes.

SpritesEffect

Default basic effect to draw 2d sprites.

Sprites3dEffect

Default basic effect to draw 2d sprites.

SpritesEffectNoVertexColor

Default basic effect to draw 2d sprites without vertex color.

SpritesWithOutlineEffect

Default basic effect to draw 2d sprites with outline.

Gfx

Gfx is the graphics manager. Everything related to rendering and managing your game canvas goes here.

To access the Graphics manager you use Shaku.gfx.

Sprite

Sprite class.

SpritesGroup

Sprites group class. This object is a container to hold sprites collection + parent transformations. You need SpritesGroup to use batched rendering.

Vertex

A vertex we can push to sprite batch.

Gamepad

Gamepad data object. This object represents a snapshot of a gamepad state, it does not update automatically.

FourButtonsCluster

Buttons cluster container - 4 buttons.

ThreeButtonsCluster

Buttons cluster container - 3 buttons.

FrontButtons

Front buttons.

Input

Input manager. Used to recieve input from keyboard and mouse.

To access the Input manager use Shaku.input.

Logger

A logger manager. By default writes logs to console.

IManager

Interface for any manager. Manager = manages a domain in Shaku, such as gfx (graphics), sfx (sounds), input, etc.

Sfx

Sfx manager. Used to play sound effects and music.

To access the Sfx manager use Shaku.sfx.

SoundInstance

A sound effect instance you can play and stop.

SoundMixer

A utility class to mix between two sounds.

Shaku

Shaku's main object. This object wraps the entire lib namespace, and this is what you use to access all managers and manage your main loop.

Animator

Implement an animator object that change values over time using Linear Interpolation. Usage example: (new Animator(sprite)).from({'position.x': 0}).to({'position.x': 100}).duration(1).play();

Box

A 3D box shape.

Circle

Implement a simple 2d Circle.

Color

Implement a color. All color components are expected to be in 0.0 - 1.0 range (and not 0-255).

Frustum

Implement a 3D Frustum shape.

GameTime

Class to hold current game time, both elapse and delta from last frame.

ItemsSorter

Utility class to arrange rectangles in minimal region.

Line

Implement a simple 2d Line.

MathHelper

Implement some math utilities functions.

Matrix

Implements a matrix.

IGrid

Interface for a supported grid.

Node

A path node.

Perlin

Generate 2d perlin noise. Based on code from noisejs by Stefan Gustavson. https://github.com/josephg/noisejs/blob/master/perlin.js

Plane

A plane in 3D space.

Ray

A 3D ray.

Rectangle

Implement a simple 2d Rectangle.

SeededRandom

Class to generate random numbers with seed.

Sphere

A 3D sphere.

Storage

A thin wrapper layer around storage utility.

StorageAdapter

Storage adapter class that implement access to a storage device. Used by the Storage utilitiy.

StorageAdapterMemory

Implement simple memory storage adapter.

StorageAdapterLocalStorage

Implement simple localstorage storage adapter.

StorageAdapterSessionStorage

Implement simple sessionStorage storage adapter.

Transformation

Transformations helper class to store 2d position, rotation and scale. Can also perform transformations inheritance, where we combine local with parent transformations.

Vector2

A simple Vector object for 2d positions.

Vector3

A Vector object for 3d positions.

Typedefs

BlendMode : String
BuffersUsage : String
UniformType : String
TextAlignment : String
TextureFilterMode : String
TextureWrapMode : String
MouseButton : Number
KeyboardKey : Number

Asset

A loadable asset base class. All asset types inherit from this.

Kind: global class

new Asset(url)

Create the new asset.

Param Type Description
url String Asset URL / identifier.

asset.ready ⇒ Boolean

Get if this asset is ready, ie loaded or created.

Kind: instance property of Asset
Returns: Boolean - True if asset finished loading / creating. This doesn’t mean its necessarily valid, only that its done loading.

asset.url ⇒ String

Get asset’s URL.

Kind: instance property of Asset
Returns: String - Asset URL.

asset.valid ⇒ Boolean

Get if this asset is loaded and valid.

Kind: instance property of Asset
Returns: Boolean - True if asset is loaded and valid, false otherwise.

asset.onReady(callback)

Register a method to be called when asset is ready. If asset is already in ready state, will invoke immediately.

Kind: instance method of Asset

Param Type Description
callback function Callback to invoke when asset is ready.

asset.waitForReady() ⇒ Promise

Return a promise to resolve when ready.

Kind: instance method of Asset
Returns: Promise - Promise to resolve when ready.

asset.load(params) ⇒ Promise

Load the asset from it’s URL.

Kind: instance method of Asset
Returns: Promise - Promise to resolve when fully loaded.

Param Type Description
params \* Optional additional params.

asset.create(source, params) ⇒ Promise

Create the asset from data source.

Kind: instance method of Asset
Returns: Promise - Promise to resolve when asset is ready.

Param Type Description
source \* Data to create asset from.
params \* Optional additional params.

asset.destroy()

Destroy the asset, freeing any allocated resources in the process.

Kind: instance method of Asset

Assets

Assets manager class. Used to create, load and cache game assets, which includes textures, audio files, JSON objects, etc. As a rule of thumb, all methods to load or create assets are async and return a promise.

To access the Assets manager you use Shaku.assets.

Kind: global class

new Assets()

Create the manager.

assets.root

Optional URL root to prepend to all loaded assets URLs. For example, if all your assets are under ‘/static/assets/’, you can set this url as root and omit it when loading assets later.

Kind: instance property of Assets

assets.suffix

Optional suffix to add to all loaded assets URLs. You can use this for anti-cache mechanism if you want to reload all assets. For example, you can set this value to “‘?dt=’ + Date.now()”.

Kind: instance property of Assets

assets.pendingAssets ⇒ Array.<string>

Get list of assets waiting to be loaded. This list will be reset if you call clearCache().

Kind: instance property of Assets
Returns: Array.<string> - URLs of assets waiting to be loaded.

assets.failedAssets ⇒ Array.<string>

Get list of assets that failed to load. This list will be reset if you call clearCache().

Kind: instance property of Assets
Returns: Array.<string> - URLs of assets that had error loading.

assets.waitForAll() ⇒ Promise

Return a promise that will be resolved only when all pending assets are loaded. If an asset fails, will reject.

Kind: instance method of Assets
Returns: Promise - Promise to resolve when all assets are loaded, or reject if there are failed assets.
Example

await Shaku.assets.waitForAll();
console.log("All assets are loaded!");

assets.getCached(url) ⇒ Asset

Get asset directly from cache, synchronous and without a Promise.

Kind: instance method of Assets
Returns: Asset - Asset or null if not loaded.

Param Type Description
url String Asset URL or name.

assets.loadSound(url) ⇒ Promise.<SoundAsset>

Load a sound asset. If already loaded, will use cache.

Kind: instance method of Assets
Returns: Promise.<SoundAsset> - promise to resolve with asset instance, when loaded. You can access the loading asset with .asset on the promise.

Param Type Description
url String Asset URL.

Example

let sound = await Shaku.assets.loadSound("assets/my_sound.ogg");

assets.loadTexture(url, [params]) ⇒ Promise.<TextureAsset>

Load a texture asset. If already loaded, will use cache.

Kind: instance method of Assets
Returns: Promise.<TextureAsset> - promise to resolve with asset instance, when loaded. You can access the loading asset with .asset on the promise.

Param Type Description
url String Asset URL.
[params] \* Optional params dictionary. See TextureAsset.load() for more details.

Example

let texture = await Shaku.assets.loadTexture("assets/my_texture.png", {generateMipMaps: false});

assets.createRenderTarget(name, width, height, [channels]) ⇒ Promise.<TextureAsset>

Create a render target texture asset. If already loaded, will use cache.

Kind: instance method of Assets
Returns: Promise.<TextureAsset> - promise to resolve with asset instance, when loaded. You can access the loading asset with .asset on the promise.

Param Type Description
name String | null Asset name (matched to URLs when using cache). If null, will not add to cache.
width Number Texture width.
height Number Texture height.
[channels] Number Texture channels count. Defaults to 4 (RGBA).

Example

let width = 512;
let height = 512;
let renderTarget = await Shaku.assets.createRenderTarget("optional_render_target_asset_id", width, height);

assets.createTextureAtlas(name, sources, [maxWidth], [maxHeight], [extraMargins]) ⇒ Promise.<TextureAtlas>

Create a texture atlas asset.

Kind: instance method of Assets
Returns: Promise.<TextureAtlas> - Promise to resolve with asset instance, when loaded. You can access the loading asset with .asset on the promise.

Param Type Description
name String | null Asset name (matched to URLs when using cache). If null, will not add to cache.
sources Array.<String> List of URLs to load textures from.
[maxWidth] Number Optional atlas textures max width.
[maxHeight] Number Optional atlas textures max height.
[extraMargins] Vector2 Optional extra empty pixels to add between textures in atlas.

assets.loadFontTexture(url, params) ⇒ Promise.<FontTextureAsset>

Load a font texture asset. If already loaded, will use cache.

Kind: instance method of Assets
Returns: Promise.<FontTextureAsset> - promise to resolve with asset instance, when loaded. You can access the loading asset with .asset on the promise.

Param Type Description
url String Asset URL.
params \* Optional params dictionary. See FontTextureAsset.load() for more details.

Example

let fontTexture = await Shaku.assets.loadFontTexture('assets/DejaVuSansMono.ttf', {fontName: 'DejaVuSansMono'});

assets.loadMsdfFontTexture(url, [params]) ⇒ Promise.<MsdfFontTextureAsset>

Load a MSDF font texture asset. If already loaded, will use cache.

Kind: instance method of Assets
Returns: Promise.<MsdfFontTextureAsset> - promise to resolve with asset instance, when loaded. You can access the loading asset with .asset on the promise.

Param Type Description
url String Asset URL.
[params] \* Optional params dictionary. See MsdfFontTextureAsset.load() for more details.

Example

let fontTexture = await Shaku.assets.loadMsdfFontTexture('DejaVuSansMono.font', {jsonUrl: 'assets/DejaVuSansMono.json', textureUrl: 'assets/DejaVuSansMono.png'});

assets.loadJson(url) ⇒ Promise.<JsonAsset>

Load a json asset. If already loaded, will use cache.

Kind: instance method of Assets
Returns: Promise.<JsonAsset> - promise to resolve with asset instance, when loaded. You can access the loading asset with .asset on the promise.

Param Type Description
url String Asset URL.

Example

let jsonData = await Shaku.assets.loadJson('assets/my_json_data.json');
console.log(jsonData.data);

assets.createJson(name, data) ⇒ Promise.<JsonAsset>

Create a new json asset. If already exist, will reject promise.

Kind: instance method of Assets
Returns: Promise.<JsonAsset> - promise to resolve with asset instance, when ready. You can access the loading asset with .asset on the promise.

Param Type Description
name String Asset name (matched to URLs when using cache). If null, will not add to cache.
data Object | String Optional starting data.

Example

let jsonData = await Shaku.assets.createJson('optional_json_data_id', {"foo": "bar"});
// you can now load this asset from anywhere in your code using 'optional_json_data_id' as url

assets.loadBinary(url) ⇒ Promise.<BinaryAsset>

Load a binary data asset. If already loaded, will use cache.

Kind: instance method of Assets
Returns: Promise.<BinaryAsset> - promise to resolve with asset instance, when loaded. You can access the loading asset with .asset on the promise.

Param Type Description
url String Asset URL.

Example

let binData = await Shaku.assets.loadBinary('assets/my_bin_data.dat');
console.log(binData.data);

assets.createBinary(name, data) ⇒ Promise.<BinaryAsset>

Create a new binary asset. If already exist, will reject promise.

Kind: instance method of Assets
Returns: Promise.<BinaryAsset> - promise to resolve with asset instance, when ready. You can access the loading asset with .asset on the promise.

Param Type Description
name String Asset name (matched to URLs when using cache). If null, will not add to cache.
data Array.<Number> | Uint8Array Binary data to set.

Example

let binData = await Shaku.assets.createBinary('optional_bin_data_id', [1,2,3,4]);
// you can now load this asset from anywhere in your code using 'optional_bin_data_id' as url

assets.free(url)

Destroy and free asset from cache.

Kind: instance method of Assets

Param Type Description
url String Asset URL to free.

Example

Shaku.assets.free("my_asset_url");

assets.clearCache()

Free all loaded assets from cache.

Kind: instance method of Assets
Example

Shaku.assets.clearCache();

BinaryAsset

A loadable binary data asset. This asset type loads array of bytes from a remote file.

Kind: global class

binaryAsset.valid

Kind: instance property of BinaryAsset

binaryAsset.data ⇒ Uint8Array

Get binary data.

Kind: instance property of BinaryAsset
Returns: Uint8Array - Data as bytes array.

binaryAsset.load() ⇒ Promise

Load the binary data from the asset URL.

Kind: instance method of BinaryAsset
Returns: Promise - Promise to resolve when fully loaded.

binaryAsset.create(source) ⇒ Promise

Create the binary data asset from array or Uint8Array.

Kind: instance method of BinaryAsset
Returns: Promise - Promise to resolve when asset is ready.

Param Type Description
source Array.<Number> | Uint8Array Data to create asset from.

binaryAsset.destroy()

Kind: instance method of BinaryAsset

binaryAsset.string() ⇒ String

Convert and return data as string.

Kind: instance method of BinaryAsset
Returns: String - Data converted to string.

FontTextureAsset

A font texture asset, dynamically generated from loaded font and canvas. This asset type creates an atlas of all the font’s characters as textures, so we can later render them as sprites.

Kind: global class

fontTextureAsset.lineHeight

Get line height.

Kind: instance property of FontTextureAsset

fontTextureAsset.fontName

Get font name.

Kind: instance property of FontTextureAsset

fontTextureAsset.fontSize

Get font size.

Kind: instance property of FontTextureAsset

fontTextureAsset.placeholderCharacter

Get placeholder character.

Kind: instance property of FontTextureAsset

fontTextureAsset.texture

Get the texture.

Kind: instance property of FontTextureAsset

fontTextureAsset.width ⇒ Number

Get texture width.

Kind: instance property of FontTextureAsset
Returns: Number - Texture width.

fontTextureAsset.height ⇒ Number

Get texture height.

Kind: instance property of FontTextureAsset
Returns: Number - Texture height.

fontTextureAsset.valid

Kind: instance property of FontTextureAsset

fontTextureAsset.load(params) ⇒ Promise

Generate the font texture from a font found in given URL.

Kind: instance method of FontTextureAsset
Returns: Promise - Promise to resolve when fully loaded.

Param Type Description
params \* Additional params. Possible values are: - fontName: mandatory font name. on some browsers if the font name does not match the font you actually load via the URL, it will not be loaded properly. - missingCharPlaceholder (default=’?’): character to use for missing characters. - smoothFont (default=true): if true, will set font to smooth mode. - fontSize (default=52): font size in texture. larget font size will take more memory, but allow for sharper text rendering in larger scales. - enforceTexturePowerOfTwo (default=true): if true, will force texture size to be power of two. - maxTextureWidth (default=1024): max texture width. - charactersSet (default=FontTextureAsset.defaultCharactersSet): which characters to set in the texture. - extraPadding (default=0,0): Optional extra padding to add around characters in texture. - sourceRectOffsetAdjustment (default=0,0): Optional extra offset in characters source rectangles. Use this for fonts that are too low / height and bleed into other characters source rectangles.

fontTextureAsset.getSize() ⇒ Vector2

Get texture size as a vector.

Kind: instance method of FontTextureAsset
Returns: Vector2 - Texture size.

fontTextureAsset.getSourceRect(character) ⇒ Rectangle

Get the source rectangle for a given character in texture.

Kind: instance method of FontTextureAsset
Returns: Rectangle - Source rectangle for character.

Param Type Description
character Character Character to get source rect for.

fontTextureAsset.getPositionOffset(character) ⇒ Vector2

When drawing the character, get the offset to add to the cursor.

Kind: instance method of FontTextureAsset
Returns: Vector2 - Offset to add to the cursor before drawing the character.

Param Type Description
character Character Character to get the offset for.

fontTextureAsset.getXAdvance(character) ⇒ Number

Get how much to advance the cursor when drawing this character.

Kind: instance method of FontTextureAsset
Returns: Number - Distance to move the cursor after drawing the character.

Param Type Description
character Character Character to get the advance for.

fontTextureAsset.destroy()

Kind: instance method of FontTextureAsset

JsonAsset

A loadable json asset. This asset type loads JSON from a remote file.

Kind: global class

jsonAsset.data ⇒ \*

Get json data.

Kind: instance property of JsonAsset
Returns: \* - Data as dictionary.

jsonAsset.valid

Kind: instance property of JsonAsset

jsonAsset.load() ⇒ Promise

Load the JSON data from the asset URL.

Kind: instance method of JsonAsset
Returns: Promise - Promise to resolve when fully loaded.

jsonAsset.create(source) ⇒ Promise

Create the JSON data asset from object or string.

Kind: instance method of JsonAsset
Returns: Promise - Promise to resolve when asset is ready.

Param Type Description
source Object | String Data to create asset from.

jsonAsset.destroy()

Kind: instance method of JsonAsset

MsdfFontTextureAsset

A MSDF font texture asset, from a pregenerated msdf texture atlas (from msdf-bmfont-xml, for example). This asset uses a signed distance field atlas to render characters as sprites at high res.

Kind: global class

msdfFontTextureAsset.width ⇒ Number

Get texture width.

Kind: instance property of MsdfFontTextureAsset
Returns: Number - Texture width.

msdfFontTextureAsset.height ⇒ Number

Get texture height.

Kind: instance property of MsdfFontTextureAsset
Returns: Number - Texture height.

msdfFontTextureAsset.load(params) ⇒ Promise

Generate the font metadata and texture from the given URL.

Kind: instance method of MsdfFontTextureAsset
Returns: Promise - Promise to resolve when fully loaded.

Param Type Description
params \* Additional params. Possible values are: - jsonUrl: mandatory url for the font’s json metadata (generated via msdf-bmfont-xml, for example) - textureUrl: mandatory url for the font’s texture atlas (generated via msdf-bmfont-xml, for example) - missingCharPlaceholder (default=’?’): character to use for missing characters.

msdfFontTextureAsset.getSize() ⇒ Vector2

Get texture size as a vector.

Kind: instance method of MsdfFontTextureAsset
Returns: Vector2 - Texture size.

msdfFontTextureAsset.getPositionOffset()

Kind: instance method of MsdfFontTextureAsset

msdfFontTextureAsset.getXAdvance()

Kind: instance method of MsdfFontTextureAsset

msdfFontTextureAsset.destroy()

Kind: instance method of MsdfFontTextureAsset

SoundAsset

A loadable sound asset. This is the asset type you use to play sounds.

Kind: global class

soundAsset.valid

Kind: instance property of SoundAsset

soundAsset.load() ⇒ Promise

Load the sound asset from its URL. Note that loading sounds isn’t actually necessary to play sounds, this method merely pre-load the asset (so first time we play the sound would be immediate and not delayed) and validate the data is valid.

Kind: instance method of SoundAsset
Returns: Promise - Promise to resolve when fully loaded.

soundAsset.destroy()

Kind: instance method of SoundAsset

TextureAsset

A loadable texture asset. This asset type loads an image from URL or source, and turn it into a texture.

Kind: global class

textureAsset.image

Kind: instance property of TextureAsset

textureAsset.width

Kind: instance property of TextureAsset

textureAsset.height

Kind: instance property of TextureAsset

textureAsset._glTexture

Kind: instance property of TextureAsset

textureAsset.valid

Kind: instance property of TextureAsset

textureAsset.load(params) ⇒ Promise

Load the texture from it’s image URL.

Kind: instance method of TextureAsset
Returns: Promise - Promise to resolve when fully loaded.

Param Type Description
params \* Optional additional params. Possible values are: - generateMipMaps (default=false): if true, will generate mipmaps for this texture. - crossOrigin (default=undefined): if set, will set the crossOrigin property with this value. - flipY (default=false): if true, will flip texture on Y axis. - premultiplyAlpha (default=false): if true, will load texture with premultiply alpha flag set.

textureAsset.createRenderTarget(width, height, channels)

Create this texture as an empty render target.

Kind: instance method of TextureAsset

Param Type Description
width Number Texture width.
height Number Texture height.
channels Number Texture channels count. Defaults to 4 (RGBA).

textureAsset.fromImage(image, params)

Create texture from loaded image instance.

Kind: instance method of TextureAsset
See: TextureAsset.load for params.

Param Type Description
image Image Image to create texture from. Image must be loaded!
params \* Optional additional params. See load() for details.

textureAsset.create(source, params) ⇒ Promise

Create the texture from an image.

Kind: instance method of TextureAsset
Returns: Promise - Promise to resolve when asset is ready.
See: TextureAsset.load for params.

Param Type Description
source Image | String Image or Image source URL to create texture from.
params \* Optional additional params. See load() for details.

textureAsset.getPixel(x, y) ⇒ Color

Get pixel color from image. Note: this method is quite slow, if you need to perform multiple queries consider using getPixelsData() once to get all pixels data instead.

Kind: instance method of TextureAsset
Returns: Color - Pixel color.

Param Type Description
x Number Pixel X value.
y Number Pixel Y value.

textureAsset.getPixelsData([x], [y], [width], [height]) ⇒ Array.<Array.<Color>>

Get a 2D array with pixel colors.

Kind: instance method of TextureAsset
Returns: Array.<Array.<Color>> - A 2D array with all texture pixel colors.

Param Type Description
[x] Number Offset X in texture to get. Defaults to 0.
[y] Number Offset Y in texture to get. Defaults to 0.
[width] Number How many pixels to get on X axis. Defaults to texture width - x.
[height] Number How many pixels to get on Y axis. Defaults to texture height - y.

textureAsset.destroy()

Kind: instance method of TextureAsset

TextureAssetBase

Base type for all texture asset types.

Kind: global class

textureAssetBase.filter

Get texture magnifying filter, or null to use default.

Kind: instance property of TextureAssetBase
See: Shaku.gfx.TextureFilterModes

textureAssetBase.filter

Set texture magnifying filter.

Kind: instance property of TextureAssetBase
See: Shaku.gfx.TextureFilterModes

Param Type Description
value TextureFilterMode Filter mode to use or null to use default.

textureAssetBase.wrapMode

Get texture wrapping mode, or null to use default.

Kind: instance property of TextureAssetBase
See: Shaku.gfx.TextureWrapModes

textureAssetBase.wrapMode

Set texture wrapping mode.

Kind: instance property of TextureAssetBase
See: Shaku.gfx.TextureWrapModes

Param Type Description
value TextureWrapMode Wrapping mode to use or null to use default.

textureAssetBase.image ⇒ Image

Get raw image.

Kind: instance property of TextureAssetBase
Returns: Image - Image instance.

textureAssetBase.width ⇒ Number

Get texture width.

Kind: instance property of TextureAssetBase
Returns: Number - Texture width.

textureAssetBase.height ⇒ Number

Get texture height.

Kind: instance property of TextureAssetBase
Returns: Number - Texture height.

textureAssetBase._glTexture

Get texture instance for WebGL.

Kind: instance property of TextureAssetBase

textureAssetBase.getSize() ⇒ Vector2

Get texture size as a vector.

Kind: instance method of TextureAssetBase
Returns: Vector2 - Texture size.

TextureAtlasAsset

A texture atlas we can build at runtime to combine together multiple textures.

Kind: global class

textureAtlasAsset.textures ⇒ Array.<TextureAsset>

Get a list with all textures in atlas.

Kind: instance property of TextureAtlasAsset
Returns: Array.<TextureAsset> - Textures in atlas.

textureAtlasAsset.valid

Kind: instance property of TextureAtlasAsset

textureAtlasAsset.getTexture(url) ⇒ TextureInAtlasAsset

Get texture asset and source rectangle for a desired image URL.

Kind: instance method of TextureAtlasAsset
Returns: TextureInAtlasAsset - Texture in atlas asset, or null if not found.

Param Type Description
url String URL to fetch texture and source from. Can be full URL, relative URL, or absolute URL starting from /.

textureAtlasAsset.destroy()

Kind: instance method of TextureAtlasAsset

TextureInAtlasAsset

A texture that is part of a texture atlas. Stores a texture that was generated by the texture atlas + the source rectangle in texture for this segment.

Kind: global class

textureInAtlasAsset.sourceRectangle ⇒ Rectangle

Return the source rectangle in texture atlas.

Kind: instance property of TextureInAtlasAsset
Returns: Rectangle - Source rectangle.

textureInAtlasAsset.sourceRectangleNormalized ⇒ Rectangle

Return the source rectangle in texture atlas, in normalized 0.0-1.0 values.

Kind: instance property of TextureInAtlasAsset
Returns: Rectangle - Source rectangle.

textureInAtlasAsset.texture ⇒ TextureAsset

Return the texture asset of this atlas texture.

Kind: instance property of TextureInAtlasAsset
Returns: TextureAsset - Texture asset.

textureInAtlasAsset.atlas ⇒ TextureAtlasAsset

Return the texture atlas class.

Kind: instance property of TextureInAtlasAsset
Returns: TextureAtlasAsset - Parent atlas.

textureInAtlasAsset.image

Kind: instance property of TextureInAtlasAsset

textureInAtlasAsset.width

Kind: instance property of TextureInAtlasAsset

textureInAtlasAsset.height

Kind: instance property of TextureInAtlasAsset

textureInAtlasAsset._glTexture

Kind: instance property of TextureInAtlasAsset

textureInAtlasAsset.valid

Kind: instance property of TextureInAtlasAsset

textureInAtlasAsset.destroy()

Kind: instance method of TextureInAtlasAsset

Collision

Collision is the collision manager. It provides basic 2d collision detection functionality. Note: this is not a physics engine, its only for detection and objects picking.

To access the Collision manager you use Shaku.collision.

Kind: global class

new Collision()

Create the manager.

collision.resolver

The collision resolver we use to detect collision between different shapes. You can use this object directly without creating a collision world, if you just need to test collision between shapes.

Kind: instance property of Collision

collision.RectangleShape

Get the collision reactanle shape class.

Kind: instance property of Collision

collision.PointShape

Get the collision point shape class.

Kind: instance property of Collision

collision.CircleShape

Get the collision circle shape class.

Kind: instance property of Collision

collision.LinesShape

Get the collision lines shape class.

Kind: instance property of Collision

collision.TilemapShape

Get the tilemap collision shape class.

Kind: instance property of Collision

collision.createWorld(gridCellSize) ⇒ CollisionWorld

Create a new collision world object.

Kind: instance method of Collision
Returns: CollisionWorld - Newly created collision world.

Param Type Description
gridCellSize Number | Vector2 Collision world grid cell size.

CollisionWorld

A collision world is a set of collision shapes that interact with each other. You can use different collision worlds to represent different levels or different parts of your game world.

Kind: global class

new CollisionWorld(resolver, gridCellSize)

Create the collision world.

Param Type Description
resolver CollisionResolver Collision resolver to use for this world.
gridCellSize Number | Vector2 For optimize collision testing, the collision world is divided into a collision grid. This param determine the grid cell size.

collisionWorld.resolver

Collision resolver used in this collision world. By default, will inherit the collision manager default resolver.

Kind: instance property of CollisionWorld

collisionWorld.stats ⇒ \*

Get current stats.

Kind: instance property of CollisionWorld
Returns: \* - Dictionary with the following stats: updatedShapes: number of times we updated or added new shapes. addedShapes: number of new shapes added. deletedGridCells: grid cells that got deleted after they were empty. createdGridCell: new grid cells created. broadPhaseShapesChecksPrePredicate: how many shapes were tested in a broadphase check, before the predicate method was called. broadPhaseShapesChecksPostPredicate: how many shapes were tested in a broadphase check, after the predicate method was called. broadPhaseCalls: how many broadphase calls were made collisionChecks: how many shape-vs-shape collision checks were actually made. collisionMatches: how many collision checks were positive.

collisionWorld.resetStats()

Reset stats.

Kind: instance method of CollisionWorld

collisionWorld.iterateShapes(callback)

Iterate all shapes in world.

Kind: instance method of CollisionWorld

Param Type Description
callback function Callback to invoke on all shapes. Return false to break iteration.

collisionWorld.addShape(shape)

Add a collision shape to this world.

Kind: instance method of CollisionWorld

Param Type Description
shape CollisionShape Shape to add.

collisionWorld.removeShape(shape)

Remove a collision shape from this world.

Kind: instance method of CollisionWorld

Param Type Description
shape CollisionShape Shape to remove.

collisionWorld.testCollision(sourceShape, sortByDistance, mask, predicate) ⇒ CollisionTestResult

Test collision with shapes in world, and return just the first result found.

Kind: instance method of CollisionWorld
Returns: CollisionTestResult - A collision test result, or null if not found.

Param Type Description
sourceShape CollisionShape Source shape to check collision for. If shape is in world, it will not collide with itself.
sortByDistance Boolean If true will return the nearest collision found (based on center of shapes).
mask Number Optional mask of bits to match against shapes collisionFlags. Will only return shapes that have at least one common bit.
predicate function Optional filter to run on any shape we’re about to test collision with. If the predicate returns false, we will skip this shape.

collisionWorld.testCollisionMany(sourceShape, sortByDistance, mask, predicate, intermediateProcessor) ⇒ Array.<CollisionTestResult>

Test collision with shapes in world, and return all results found.

Kind: instance method of CollisionWorld
Returns: Array.<CollisionTestResult> - An array of collision test results, or empty array if none found.

Param Type Description
sourceShape CollisionShape Source shape to check collision for. If shape is in world, it will not collide with itself.
sortByDistance Boolean If true will sort results by distance.
mask Number Optional mask of bits to match against shapes collisionFlags. Will only return shapes that have at least one common bit.
predicate function Optional filter to run on any shape we’re about to test collision with. If the predicate returns false, we will skip this shape.
intermediateProcessor function Optional method to run after each positive result with the collision result as param. Return false to stop and return results.

collisionWorld.pick(position, radius, sortByDistance, mask, predicate) ⇒ Array.<CollisionShape>

Return array of shapes that touch a given position, with optional radius.

Kind: instance method of CollisionWorld
Returns: Array.<CollisionShape> - Array with collision shapes we picked.

Param Type Description
position \* Position to pick.
radius \* Optional picking radius to use a circle instead of a point.
sortByDistance \* If true, will sort results by distance from point.
mask \* Collision mask to filter by.
predicate \* Optional predicate method to filter by.

Example

let shapes = world.pick(Shaku.input.mousePosition);

collisionWorld.setDebugDrawBatch(batch)

Set the shapes batch to use for debug-drawing this collision world.

Kind: instance method of CollisionWorld

Param Type Description
batch ShapesBatch Batch to use for debug draw.

collisionWorld.getOrCreateDebugDrawBatch() ⇒ ShapesBatch

Return the currently set debug draw batch, or create a new one if needed.

Kind: instance method of CollisionWorld
Returns: ShapesBatch - Shapes batch instance used to debug-draw collision world.

collisionWorld.debugDraw(gridColor, gridHighlitColor, opacity, camera)

Debug-draw the current collision world.

Kind: instance method of CollisionWorld

Param Type Description
gridColor Color Optional grid color (default to black).
gridHighlitColor Color Optional grid color for cells with shapes in them (default to red).
opacity Number Optional opacity factor (default to 0.5).
camera Camera Optional camera for offset and viewport.

CollisionResolver

The collision resolver is responsible to implement collision detection between pair of shapes of same or different types.

Kind: global class

new CollisionResolver()

Create the resolver.

collisionResolver.setHandler(firstShapeId, secondShapeId, handler)

Set the method used to test collision between two shapes. Note: you don’t need to register the same handler twice for reverse order, its done automatically inside.

Kind: instance method of CollisionResolver

Param Type Description
firstShapeId String The shape identifier the handler recieves as first argument.
secondShapeId String The shape identifier the handler recieves as second argument.
handler function Method to test collision between the shapes. Return false if don’t collide, return either Vector2 with collision position or ‘true’ for collision.

collisionResolver.test(first, second) ⇒ CollisionTestResult

Check a collision between two shapes.

Kind: instance method of CollisionResolver
Returns: CollisionTestResult - collision detection result or null if they don’t collide.

Param Type Description
first CollisionShape First collision shape to test.
second CollisionShape Second collision shape to test.

collisionResolver.testWithHandler(first, second, handler) ⇒ CollisionTestResult

Check a collision between two shapes.

Kind: instance method of CollisionResolver
Returns: CollisionTestResult - collision detection result or null if they don’t collide.

Param Type Description
first CollisionShape First collision shape to test.
second CollisionShape Second collision shape to test.
handler function Method to test collision between the shapes.

collisionResolver.getHandlers()

Get handlers dictionary for a given shape.

Kind: instance method of CollisionResolver

CollisionTestResult

Collision detection result.

Kind: global class

new CollisionTestResult(position, first, second)

Create the collision result.

Param Type Description
position Vector2 Optional collision position.
first CollisionShape First shape in the collision check.
second CollisionShape Second shape in the collision check.

collisionTestResult.position : Vector2

Collision position, only relevant when there’s a single touching point. For shapes with multiple touching points, this will be null.

Kind: instance property of CollisionTestResult

collisionTestResult.first : CollisionShape

First collided shape.

Kind: instance property of CollisionTestResult

collisionTestResult.second : CollisionShape

Second collided shape.

Kind: instance property of CollisionTestResult

CircleShape

Collision circle class.

Kind: global class

new CircleShape(circle)

Create the collision shape.

Param Type Description
circle Circle the circle shape.

circleShape.shapeId

Kind: instance property of CircleShape

circleShape.setShape(circle)

Set this collision shape from circle.

Kind: instance method of CircleShape

Param Type Description
circle Circle Circle shape.

circleShape._getRadius()

Kind: instance method of CircleShape

circleShape.getCenter()

Kind: instance method of CircleShape

circleShape._getBoundingBox()

Kind: instance method of CircleShape

circleShape.debugDraw()

Kind: instance method of CircleShape

LinesShape

Collision lines class. This shape is made of one line or more.

Kind: global class

new LinesShape(lines)

Create the collision shape.

Param Type Description
lines Array.<Line> | Line Starting line / lines.

linesShape.shapeId

Kind: instance property of LinesShape

linesShape.addLines(lines)

Add line or lines to this collision shape.

Kind: instance method of LinesShape

Param Type Description
lines Array.<Line> | Line Line / lines to add.

linesShape.setLines(lines)

Set this shape from line or lines array.

Kind: instance method of LinesShape

Param Type Description
lines Array.<Line> | Line Line / lines to set.

linesShape._getRadius()

Kind: instance method of LinesShape

linesShape.getCenter()

Kind: instance method of LinesShape

linesShape._getBoundingBox()

Kind: instance method of LinesShape

linesShape.debugDraw()

Kind: instance method of LinesShape

PointShape

Collision point class.

Kind: global class

new PointShape(position)

Create the collision shape.

Param Type Description
position Vector2 Point position.

pointShape.shapeId

Kind: instance property of PointShape

pointShape.setPosition(position)

Set this collision shape from vector2.

Kind: instance method of PointShape

Param Type Description
position Vector2 Point position.

pointShape.getPosition() ⇒ Vector2

Get point position.

Kind: instance method of PointShape
Returns: Vector2 - Point position.

pointShape.getCenter()

Kind: instance method of PointShape

pointShape._getRadius()

Kind: instance method of PointShape

pointShape._getBoundingBox()

Kind: instance method of PointShape

pointShape.debugDraw(opacity)

Debug draw this shape.

Kind: instance method of PointShape

Param Type Description
opacity Number Shape opacity factor.

RectangleShape

Collision rectangle class.

Kind: global class

new RectangleShape(rectangle)

Create the collision shape.

Param Type Description
rectangle Rectangle the rectangle shape.

rectangleShape.shapeId

Kind: instance property of RectangleShape

rectangleShape.setShape(rectangle)

Set this collision shape from rectangle.

Kind: instance method of RectangleShape

Param Type Description
rectangle Rectangle Rectangle shape.

rectangleShape._getRadius()

Kind: instance method of RectangleShape

rectangleShape._getBoundingBox()

Kind: instance method of RectangleShape

rectangleShape.getCenter()

Kind: instance method of RectangleShape

rectangleShape.debugDraw()

Kind: instance method of RectangleShape

CollisionShape

Collision shape base class.

Kind: global class

new CollisionShape()

Create the collision shape.

collisionShape.shapeId ⇒ String

Get the collision shape’s unique identifier.

Kind: instance property of CollisionShape
Returns: String - Shape’s unique identifier

collisionShape.collisionFlags

Get collision flags (matched against collision mask when checking collision).

Kind: instance property of CollisionShape

collisionShape.collisionFlags

Set collision flags (matched against collision mask when checking collision).

Kind: instance property of CollisionShape

collisionShape.setDebugColor(color)

Set the debug color to use to draw this shape.

Kind: instance method of CollisionShape

Param Type Description
color Color Color to set or null to use default.

collisionShape.debugDraw(opacity, shapesBatch)

Debug draw this shape.

Kind: instance method of CollisionShape

Param Type Description
opacity Number Shape opacity factor.
shapesBatch ShapesBatch Optional shapes batch to use to debug draw the shape. By default will use the collision world.

collisionShape.getCenter() ⇒ Vector2

Get shape center position.

Kind: instance method of CollisionShape
Returns: Vector2 - Center position.

collisionShape.remove()

Remove self from parent world object.

Kind: instance method of CollisionShape

TilemapShape

Collision tilemap class. A collision tilemap shape is a grid of equal-sized cells that can either block or not (+ have collision flags). Its the most efficient (both memory and CPU) way to implement grid based / tilemap collision.

Kind: global class

new TilemapShape(offset, gridSize, tileSize, borderThickness)

Create the collision tilemap.

Param Type Description
offset Vector2 Tilemap top-left corner.
gridSize Vector2 Number of tiles on X and Y axis.
tileSize Vector2 The size of a single tile.
borderThickness Number Set a border collider with this thickness.

tilemapShape.shapeId

Kind: instance property of TilemapShape

tilemapShape.setTile(index, haveCollision, collisionFlags)

Set the state of a tile.

Kind: instance method of TilemapShape

Param Type Description
index Vector2 Tile index.
haveCollision Boolean Does this tile have collision?
collisionFlags Number Optional collision flag to set for this tile.

tilemapShape.getTileAt(position) ⇒ RectangleShape

Get the collision shape of a tile at a given position.

Kind: instance method of TilemapShape
Returns: RectangleShape - Collision shape at this position, or null if not set.

Param Type Description
position Vector2 Position to get tile at.

tilemapShape.iterateTilesAtRegion(region, callback)

Iterate all tiles in given region, represented by a rectangle.

Kind: instance method of TilemapShape

Param Type Description
region Rectangle Rectangle to get tiles for.
callback function Method to invoke for every tile. Return false to break iteration.

tilemapShape.getTilesAtRegion(region) ⇒ Array.<RectangleShape>

Get all tiles in given region, represented by a rectangle.

Kind: instance method of TilemapShape
Returns: Array.<RectangleShape> - Array with rectangle shapes or empty if none found.

Param Type Description
region Rectangle Rectangle to get tiles for.

tilemapShape._getRadius()

Kind: instance method of TilemapShape

tilemapShape._getBoundingBox()

Kind: instance method of TilemapShape

tilemapShape.getCenter()

Kind: instance method of TilemapShape

tilemapShape.debugDraw()

Kind: instance method of TilemapShape

Camera

Implements a Camera object.

Kind: global class

new Camera(gfx)

Create the camera.

Param Type Description
gfx Gfx The gfx manager instance.

camera.viewport ⇒ Rectangle

Get camera’s viewport (drawing region to set when using this camera).

Kind: instance property of Camera
Returns: Rectangle - Camera’s viewport as rectangle.

camera.viewport

Set camera’s viewport.

Kind: instance property of Camera

Param Type Description
viewport Rectangle New viewport to set or null to not use any viewport when using this camera.

camera.getRegion() ⇒ Rectangle

Get the region this camera covers.

Kind: instance method of Camera
Returns: Rectangle - region this camera covers.

camera.orthographicOffset(offset, ignoreViewportSize, near, far)

Make this camera an orthographic camera with offset.

Kind: instance method of Camera

Param Type Description
offset Vector2 Camera offset (top-left corner).
ignoreViewportSize Boolean If true, will take the entire canvas size for calculation and ignore the viewport size, if set.
near Number Near clipping plane.
far Number Far clipping plane.

camera.orthographic(region, near, far)

Make this camera an orthographic camera.

Kind: instance method of Camera

Param Type Description
region Rectangle Camera left, top, bottom and right. If not set, will take entire canvas.
near Number Near clipping plane.
far Number Far clipping plane.

Camera3D

Implements a 3d Camera object.

Kind: global class

new Camera3D(gfx)

Create the camera.

Param Type Description
gfx Gfx The gfx manager instance.

camera3D.projection

Camera projection matrix. You can set it manually, or use ‘orthographicOffset’ / ‘orthographic’ / ‘perspective’ helper functions.

Kind: instance property of Camera3D

camera3D.view

Camera view matrix. You can set it manually, or use ‘setViewLookat’ helper function.

Kind: instance property of Camera3D

camera3D.calcVisibleFrustum() ⇒ Frustum

Calc and return the currently-visible view frustum, based on active camera.

Kind: instance method of Camera3D
Returns: Frustum - Visible frustum.

camera3D.setViewLookat([eyePosition], [lookAt])

Set camera view matrix from source position and lookat.

Kind: instance method of Camera3D

Param Type Description
[eyePosition] Vector3 Camera source position.
[lookAt] Vector3 Camera look-at target.

camera3D.getDirection() ⇒ Vector3

Get 3d direction vector of this camera.

Kind: instance method of Camera3D
Returns: Vector3 - 3D direction vector.

camera3D.getViewProjection() ⇒ Matrix

Get view projection matrix.

Kind: instance method of Camera3D
Returns: Matrix - View-projection matrix.

camera3D.getProjectionView() ⇒ Matrix

Get projection view matrix.

Kind: instance method of Camera3D
Returns: Matrix - Projection-view matrix.

camera3D.perspective(fieldOfView, aspectRatio, near, far)

Make this camera a perspective camera.

Kind: instance method of Camera3D

Param Type Description
fieldOfView \* Field of view angle in radians.
aspectRatio \* Aspect ratio.
near \* Near clipping plane.
far \* Far clipping plane.

camera3D.unproject(point, zDistance) ⇒ Vector3

Unproject a 2d vector into 3D space. You can use this method to get the 3D direction the user points on with the mouse.

Kind: instance method of Camera3D
Returns: Vector3 - Unprojected point in 3D space.

Param Type Default Description
point Vector2   Vector to unproject.
zDistance Number 0 Distance from camera to locate the 3D point at (0 = near plane, 1 = far plane).

DrawBatch

Base class for a drawing batch, used to draw a collection of sprites or shapes.

Kind: global class

new DrawBatch()

Create the draw batch.

drawBatch.defaultEffect ⇒ Effect

Get the default effect to use for this drawing batch type.

Kind: instance property of DrawBatch
Returns: Effect - Default effect to use for this drawing batch.

drawBatch.BuffersUsage

Get the BuffersUsage enum.

Kind: instance property of DrawBatch
See: BuffersUsage

drawBatch.isDestroyed ⇒ Boolean

Return if the batch was destroyed.

Kind: instance property of DrawBatch
Returns: Boolean - True if batch was destoryed.

drawBatch.isDrawing ⇒ Boolean

Return if the batch is currently drawing.

Kind: instance property of DrawBatch
Returns: Boolean - If the batch began drawing.

drawBatch.isStatic ⇒ Boolean

Return if this batch was turned static.

Kind: instance property of DrawBatch
Returns: Boolean - True if its a static batch you can no longer change.

drawBatch.defaultBlendMode

Get the default blend mode to use for this drawing batch.

Kind: instance property of DrawBatch

drawBatch.makeStatic()

Make the batch buffers static. This means you won’t be able to change the drawings in this batch once end() is called, but you’ll be able to redraw the batch with different effects and transformations without copying any data, and much faster. This also free up some internal arrays, thus reducing the memory used for this batch. Note: must be called after ‘begin()’ and right before the ‘end()’ call.

Kind: instance method of DrawBatch

drawBatch.destroy()

Destroy the batch and free any resources assigned to it.

Kind: instance method of DrawBatch

drawBatch.setBuffersUsage(usage)

Set the way we mark the buffers we pass to the GPU based on expected behavior. Use StreamDraw if you want to set buffers once, and use them in GPU few times. Use DynamicDraw if you want to set buffers many times, and use them in GPU many times. Use StaticDraw if you want to set buffers once, and use them in GPU many times.

Kind: instance method of DrawBatch

Param Type Description
usage BuffersUsage Buffers usage.

drawBatch.begin([blendMode], [effect], [transform], [overrideEffectFlags])

Start drawing this batch. You must call this before doing any draw calls.

Kind: instance method of DrawBatch

Param Type Description
[blendMode] BlendModes Blend mode to draw this batch in.
[effect] Effect Effect to use. If not defined will use this batch type default effect.
[transform] Matrix Optional transformations to apply on all sprites.
[overrideEffectFlags] \* Optional flags to override effect’s defaults. Possible keys: {enableDepthTest, enableFaceCulling, enableStencilTest, enableDithering}.

drawBatch.endWithoutDraw()

Finish drawing without presenting on screen.

Kind: instance method of DrawBatch

drawBatch.end()

End drawing and present whatever left in buffers on screen.

Kind: instance method of DrawBatch

drawBatch.present()

Draw whatever is currently in buffers without ending the draw batch.

Kind: instance method of DrawBatch

drawBatch.clear()

Clear this buffer from any drawings in it. Called internally if ‘preserveBuffers’ is not true.

Kind: instance method of DrawBatch

LinesBatch

Colored lines renderer. Responsible to drawing a batch of line segments or strips.

Kind: global class

new LinesBatch([lineSegmentsCount])

Create the sprites batch.

Param Type Description
[lineSegmentsCount] Number Internal buffers size, in line segments count (line segment = 3 vertices). Bigger value = faster rendering but more RAM.

linesBatch.isDestroyed

Kind: instance property of LinesBatch

linesBatch.defaultEffect

Kind: instance property of LinesBatch

linesBatch.linesInBatch ⇒ Number

Get how many line segments are currently in batch.

Kind: instance property of LinesBatch
Returns: Number - Line segments in batch count.

linesBatch.maxLinesCount ⇒ Number

Get how many line segments this batch can contain.

Kind: instance property of LinesBatch
Returns: Number - Max line segments count.

linesBatch.isFull ⇒ Boolean

Check if this batch is full.

Kind: instance property of LinesBatch
Returns: Boolean - True if batch is full.

linesBatch.clear()

Kind: instance method of LinesBatch

linesBatch.destroy()

Kind: instance method of LinesBatch

linesBatch.drawVertices(vertices)

Push vertices to drawing batch.

Kind: instance method of LinesBatch

Param Type Description
vertices Array.<Vertex> Vertices to push. Vertices count must be dividable by 3 to keep the batch consistent of polygons.

linesBatch.drawQuad(position, size, color, [rotation], [origin], [skew])

Add a rectangle to draw.

Kind: instance method of LinesBatch

Param Type Description
position Vector2 | Vector3 Drawing position (at origin). If vector3 is provided, will pass z value to the shader code position attribute.
size Vector2 | Vector3 | Number Drawing size. If vector3 is provided, will pass z value to the shader code position attribute for the bottom vertices, as position.z + size.z.
color Color | Array.<Color> | undefined Rectangle color, or undefined to not change color. If array is set, will assign each color to different vertex, starting from top-left.
[rotation] Number Rotate rectangle.
[origin] Vector2 Drawing origin. This will be the point at ‘position’ and rotation origin.
[skew] Vector2 Skew the drawing corners on X and Y axis, around the origin point.

linesBatch.drawRectangle(destRect, [sourceRect], color, [rotation], [origin])

Add a rectangle that covers a given destination rectangle.

Kind: instance method of LinesBatch

Param Type Description
destRect Rectangle | Vector2 Destination rectangle to draw on. If vector is provided, will draw from 0,0 with vector as size.
[sourceRect] Rectangle Source rectangle, or undefined to use the entire texture.
color Color | Array.<Color> | undefined Rectangle color, or undefined to not change color. If array is set, will assign each color to different vertex, starting from top-left.
[rotation] Number Rotate rectangle.
[origin] Vector2 Drawing origin. This will be the point at ‘position’ and rotation origin.

linesBatch.drawCircle(circle, color, [segmentsCount], ratio, [rotation])

Draw a colored circle.

Kind: instance method of LinesBatch

Param Type Description
circle Circle Circle to draw.
color Color Circle fill color.
[segmentsCount] Number How many segments to build the circle from (more segments = smoother circle).
ratio Number | Vector2 If procided, will scale the circle on X and Y axis to turn it into an oval. If a number is provided, will use this number to scale Y axis.
[rotation] Number If provided will rotate the oval / circle.

ShapesBatch

Colored shapes renderer. Responsible to drawing a batch of basic geometric shapes with as little draw calls as possible.

Kind: global class

new ShapesBatch([batchPolygonsCount])

Create the sprites batch.

Param Type Description
[batchPolygonsCount] Number Internal buffers size, in polygons count (polygon = 3 vertices). Bigger value = faster rendering but more RAM.

shapesBatch.onOverflow : function

Optional method to trigger when shapes batch overflows and can’t contain any more polygons.

Kind: instance property of ShapesBatch

shapesBatch.snapPixels : Boolean

If true, will floor vertices positions before pushing them to batch.

Kind: instance property of ShapesBatch

shapesBatch.linesStrip : Boolean

If true, will draw lines as a single lines strip.

Kind: instance property of ShapesBatch

shapesBatch.onOverflow : function

Optional method to trigger when shapes batch overflows and can’t contain any more polygons.

Kind: instance property of ShapesBatch

shapesBatch.snapPixels : Boolean

If true, will floor vertices positions before pushing them to batch.

Kind: instance property of ShapesBatch

shapesBatch.isDestroyed

Kind: instance property of ShapesBatch

shapesBatch.defaultEffect

Kind: instance property of ShapesBatch

shapesBatch.polygonsInBatch ⇒ Number

Get how many polygons are currently in batch.

Kind: instance property of ShapesBatch
Returns: Number - Polygons in batch count.

shapesBatch.maxPolygonsCount ⇒ Number

Get how many polygons this sprite batch can contain.

Kind: instance property of ShapesBatch
Returns: Number - Max polygons count.

shapesBatch.isFull ⇒ Boolean

Check if this batch is full.

Kind: instance property of ShapesBatch
Returns: Boolean - True if batch is full.

shapesBatch.clear()

Kind: instance method of ShapesBatch

shapesBatch.destroy()

Kind: instance method of ShapesBatch

shapesBatch.drawLine(fromPoint, toPoint, color, [width])

Draw a line between two points. This method actually uses a rectangle internally, which is less efficient than using a proper LinesBatch, but have the advantage of supporting width.

Kind: instance method of ShapesBatch

Param Type Description
fromPoint Vector2 Starting position.
toPoint Vector2 Ending position.
color Color Line color.
[width] Number Line width.

shapesBatch.drawVertices(vertices)

Push vertices to drawing batch.

Kind: instance method of ShapesBatch

Param Type Description
vertices Array.<Vertex> Vertices to push. Vertices count must be dividable by 3 to keep the batch consistent of polygons.

shapesBatch.drawQuad(position, size, color, [rotation], [origin], [skew])

Add a rectangle to draw.

Kind: instance method of ShapesBatch

Param Type Description
position Vector2 | Vector3 Drawing position (at origin). If vector3 is provided, will pass z value to the shader code position attribute.
size Vector2 | Vector3 | Number Drawing size. If vector3 is provided, will pass z value to the shader code position attribute for the bottom vertices, as position.z + size.z.
color Color | Array.<Color> | undefined Rectangle color, or undefined to not change color. If array is set, will assign each color to different vertex, starting from top-left.
[rotation] Number Rotate rectangle.
[origin] Vector2 Drawing origin. This will be the point at ‘position’ and rotation origin.
[skew] Vector2 Skew the drawing corners on X and Y axis, around the origin point.

shapesBatch.addPoint(position, color)

Adds a 1x1 point.

Kind: instance method of ShapesBatch

Param Type Description
position Vector2 | Vector3 Point position.
color Color Point color.

shapesBatch.drawRectangle(destRect, color, [rotation], [origin])

Add a rectangle that covers a given destination rectangle.

Kind: instance method of ShapesBatch

Param Type Description
destRect Rectangle | Vector2 Destination rectangle to draw on. If vector is provided, will draw from 0,0 with vector as size.
color Color | Array.<Color> | undefined Rectangle color, or undefined to not change color. If array is set, will assign each color to different vertex, starting from top-left.
[rotation] Number Rotate rectangle.
[origin] Vector2 Drawing origin. This will be the point at ‘position’ and rotation origin.

shapesBatch.drawCircle(circle, color, [segmentsCount], [outsideColor], ratio, [rotation])

Draw a colored circle.

Kind: instance method of ShapesBatch

Param Type Description
circle Circle Circle to draw.
color Color Circle fill color.
[segmentsCount] Number How many segments to build the circle from (more segments = smoother circle).
[outsideColor] Color If provided, will create a gradient-colored circle and this value will be the outter side color.
ratio Number | Vector2 If procided, will scale the circle on X and Y axis to turn it into an oval. If a number is provided, will use this number to scale Y axis.
[rotation] Number If provided will rotate the oval / circle.

SpriteBatch

Sprite batch renderer. Responsible to drawing a batch of sprites with as little draw calls as possible.

Kind: global class

new SpriteBatch([batchSpritesCount], [enableVertexColor], [enableNormals], [enableBinormals], [enableTangents])

Create the sprites batch.

Param Type Description
[batchSpritesCount] Number Internal buffers size, in sprites count (sprite = 4 vertices). Bigger value = faster rendering but more RAM.
[enableVertexColor] Boolean If true (default) will support vertex color.
[enableNormals] Boolean If true (not default) will support vertex normals.
[enableBinormals] Boolean If true (not default) will support vertex binormals.
[enableTangents] Boolean If true (not default) will support vertex tangents.

spriteBatch.defaultEffect

Kind: instance property of SpriteBatch

spriteBatch.onOverflow : function

Optional method to trigger when sprite batch overflows and can’t contain any more quads.

Kind: instance property of SpriteBatch

spriteBatch.beforeDraw : function

Optional method to trigger right before drawing this batch. Receive params: effect, texture.

Kind: instance property of SpriteBatch

spriteBatch.snapPixels : Boolean

If true, will floor vertices positions before pushing them to batch.

Kind: instance property of SpriteBatch

spriteBatch.cullOutOfScreen : Boolean

If true, will cull quads that are not visible in screen when adding them by default. Note: will cull based on screen region during the time of adding sprite, not the time of actually rendering it.

Kind: instance property of SpriteBatch

spriteBatch.drawVertices(texture, vertices)

Push vertices to drawing batch.

Kind: instance method of SpriteBatch

Param Type Description
texture TextureAssetBase Texture to draw.
vertices Array.<Vertex> Vertices to push. Vertices count must be dividable by 4 to keep the batch consistent of quads.

spriteBatch.drawQuad(texture, position, size, sourceRectangle, color, [rotation], [origin], [skew])

Add a quad to draw.

Kind: instance method of SpriteBatch

Param Type Description
texture TextureAssetBase Texture to draw.
position Vector2 | Vector3 Drawing position (at origin). If vector3 is provided, will pass z value to the shader code position attribute.
size Vector2 | Vector3 | Number Drawing size. If vector3 is provided, will pass z value to the shader code position attribute for the bottom vertices, as position.z + size.z.
sourceRectangle Rectangle Source rectangle, or undefined to use the entire texture.
color Color | Array.<Color> | undefined Tint color, or undefined to not change color. If array is set, will assign each color to different vertex, starting from top-left.
[rotation] Number Rotate sprite.
[origin] Vector2 Drawing origin. This will be the point at ‘position’ and rotation origin.
[skew] Vector2 Skew the drawing corners on X and Y axis, around the origin point.

spriteBatch.drawSpriteGroup(group, [cullOutOfScreen])

Add sprites group to this batch.

Kind: instance method of SpriteBatch

Param Type Description
group SpritesGroup Sprite group to draw.
[cullOutOfScreen] Boolean If true, will cull sprites that are not visible in currently set rendering region.

spriteBatch.drawRectangle(texture, destRect, [sourceRect], color, [origin])

Add a quad that covers a given destination rectangle.

Kind: instance method of SpriteBatch

Param Type Description
texture TextureAssetBase Texture to draw.
destRect Rectangle | Vector2 Destination rectangle to draw on. If vector is provided, will draw from 0,0 with vector as size.
[sourceRect] Rectangle Source rectangle, or undefined to use the entire texture.
color Color | Array.<Color> | undefined Tint color, or undefined to not change color. If array is set, will assign each color to different vertex, starting from top-left.
[origin] Vector2 Drawing origin. This will be the point at ‘position’ and rotation origin.

SpriteBatch3D

3D Sprites batch renderer. Responsible to drawing 3D quads with textures on them.

Kind: global class

new SpriteBatch3D([batchSpritesCount], [enableNormals], [enableBinormals], [enableTangents])

Create the 3d sprites batch.

Param Type Description
[batchSpritesCount] Number Internal buffers size, in sprites count (sprite = 4 vertices). Bigger value = faster rendering but more RAM.
[enableNormals] Boolean If true (not default) will support vertex normals.
[enableBinormals] Boolean If true (not default) will support vertex binormals.
[enableTangents] Boolean If true (not default) will support vertex tangents.

spriteBatch3D.camera ⇒ Camera

Get camera instance.

Kind: instance property of SpriteBatch3D
Returns: Camera - Camera instance.

spriteBatch3D.supportVertexColor

Kind: instance property of SpriteBatch3D

spriteBatch3D.defaultEffect

Kind: instance property of SpriteBatch3D

spriteBatch3D.setPerspectiveCamera([fieldOfView], [aspectRatio], [zNear], [zFar])

Set perspective camera.

Kind: instance method of SpriteBatch3D

Param Type Description
[fieldOfView] Number Camera field of view.
[aspectRatio] Number Camera aspect ratio
[zNear] Number Z near plane.
[zFar] Number Z far plane.

spriteBatch3D.setCamera(camera)

Set the camera for this batch.

Kind: instance method of SpriteBatch3D

Param Type Description
camera Camera Camera object to apply when drawing, or null if you want to set the camera manually.

SpriteBatchBase

Base class for sprite-based rendering, ie vertices with textures.

Kind: global class

new SpriteBatchBase([batchSpritesCount], [enableVertexColor], [enableNormals], [enableBinormals], [enableTangents])

Create the sprites batch.

Param Type Description
[batchSpritesCount] Number Internal buffers size, in sprites count (sprite = 4 vertices). Bigger value = faster rendering but more RAM.
[enableVertexColor] Boolean If true (default) will support vertex color.
[enableNormals] Boolean If true (not default) will support vertex normals.
[enableBinormals] Boolean If true (not default) will support vertex binormals.
[enableTangents] Boolean If true (not default) will support vertex tangents.

spriteBatchBase.isDestroyed

Kind: instance property of SpriteBatchBase

spriteBatchBase.supportVertexColor ⇒ Boolean

Get if this sprite batch support vertex color.

Kind: instance property of SpriteBatchBase
Returns: Boolean - True if support vertex color.

spriteBatchBase.defaultEffect

Kind: instance property of SpriteBatchBase

spriteBatchBase.quadsInBatch ⇒ Number

Get how many quads are currently in batch.

Kind: instance property of SpriteBatchBase
Returns: Number - Quads in batch count.

spriteBatchBase.maxQuadsCount ⇒ Number

Get how many quads this sprite batch can contain.

Kind: instance property of SpriteBatchBase
Returns: Number - Max quads count.

spriteBatchBase.isFull ⇒ Boolean

Check if this batch is full.

Kind: instance property of SpriteBatchBase
Returns: Boolean - True if batch is full.

spriteBatchBase.destroy()

Kind: instance method of SpriteBatchBase

spriteBatchBase.clear()

Kind: instance method of SpriteBatchBase

spriteBatchBase.drawSprite(sprites, [transform], [cullOutOfScreen])

Add sprite or sprites to batch.

Kind: instance method of SpriteBatchBase

Param Type Description
sprites Sprite | Array.<Sprite> Sprite or multiple sprites to draw.
[transform] Matrix Optional transformations to apply on sprite vertices. Won’t apply on static sprites.
[cullOutOfScreen] Boolean If true, will cull sprites that are not visible in currently set rendering region.

TextSpriteBatch

Text sprite batch renderer. Responsible to drawing a batch of characters sprites.

Kind: global class

new TextSpriteBatch([batchSpritesCount])

Create the text sprites batch.

Param Type Description
[batchSpritesCount] Number Internal buffers size, in sprites count (sprite = 4 vertices). Bigger value = faster rendering but more RAM.

textSpriteBatch.msdfFont : Boolean

If true, will render as Msdf Fonts.

Kind: instance property of TextSpriteBatch

textSpriteBatch.outlineWeight : Number

If bigger than 0, will draw outline. Currently not supported with msdf fonts. Must be set before begin() is called.

Kind: instance property of TextSpriteBatch

textSpriteBatch.outlineColor : Color

Outline color, when outlineWeight is set. Must be set before begin() is called.

Kind: instance property of TextSpriteBatch

textSpriteBatch.defaultEffect

Kind: instance property of TextSpriteBatch

textSpriteBatch.drawText(textGroup, cullOutOfScreen)

Add text sprites group to batch.

Kind: instance method of TextSpriteBatch

Param Type Description
textGroup SpritesGroup Text sprite group to draw.
cullOutOfScreen Boolean If true, will cull out sprites that are not visible in screen.

Effect

Effect base class. An effect = vertex shader + fragment shader + uniforms & attributes + setup code.

Kind: global class

new Effect()

Create the effect.

effect.uniformTypes ⇒ \*

Get a dictionary with all shaders uniforms. Key = uniform name, as appears in shader code. Value = { type: UniformTypes to represent uniform type, bind: Optional bind to one of the built-in uniforms. See Effect.UniformBinds for details. }

Kind: instance property of Effect
Returns: \* - Dictionary with uniforms descriptions.

effect.attributeTypes ⇒ \*

Get a dictionary with all shader attributes. Key = attribute name, as appears in shader code. Value = { size: size of every value in this attribute. type: attribute type. See Effect.AttributeTypes for details. normalize: if true, will normalize values. stride: optional stride. offset: optional offset. bind: Optional bind to one of the built-in attributes. See Effect.AttributeBinds for details. }

Kind: instance property of Effect
Returns: \* - Dictionary with attributes descriptions.

effect.vertexCode ⇒ String

Get this effect’s vertex shader code, as string.

Kind: instance property of Effect
Returns: String - Vertex shader code.

effect.fragmentCode ⇒ String

Get this effect’s fragment shader code, as string.

Kind: instance property of Effect
Returns: String - Fragment shader code.

effect.enableDepthTest

Should this effect enable depth test?

Kind: instance property of Effect

effect.enableFaceCulling

Should this effect enable face culling?

Kind: instance property of Effect

effect.depthFunc

Get depth func to use when rendering using this effect. Use ‘DepthFuncs’ to get options.

Kind: instance property of Effect

effect.enableStencilTest

Should this effect enable stencil test?

Kind: instance property of Effect

effect.enableDithering

Should this effect enable dithering?

Kind: instance property of Effect

effect.polygonOffset ⇒ Boolean | \*

Get polygon offset factor, to apply on depth value before checking.

Kind: instance property of Effect
Returns: Boolean | \* - Return false to disable polygon offset, or {factor, unit} to apply polygon offset.

effect.hasVertexColor ⇒ Boolean

Return if this effect have colors attribute on vertices.

Kind: instance property of Effect
Returns: Boolean - True if got vertices color attribute.

effect.setAsActive(overrideFlags)

Make this effect active.

Kind: instance method of Effect

Param Type Description
overrideFlags \* Optional flags to override in effect. May include the following: enableDepthTest, enableFaceCulling, enableStencilTest, enableDithering.

effect.getBoundUniform(bindKey) ⇒

Get a uniform method from a bind key.

Kind: instance method of Effect
Returns: Uniform set method, or null if not set.

Param Type Description
bindKey UniformBinds Uniform bind key.

effect.setTexture(texture) ⇒ Boolean

Set the main texture. Note: this will only work for effects that utilize the ‘MainTexture’ uniform.

Kind: instance method of Effect
Returns: Boolean - True if texture was changed, false if there was no need to change the texture.

Param Type Description
texture TextureAssetBase Texture to set.

effect.setColor(color)

Set the main tint color. Note: this will only work for effects that utilize the ‘Color’ uniform.

Kind: instance method of Effect

Param Type Description
color Color Color to set.

effect.setProjectionMatrix(matrix)

Set the projection matrix uniform. Note: this will only work for effects that utilize the ‘Projection’ uniform.

Kind: instance method of Effect

Param Type Description
matrix Matrix Matrix to set.

effect.setWorldMatrix(matrix)

Set the world matrix uniform. Note: this will only work for effects that utilize the ‘World’ uniform.

Kind: instance method of Effect

Param Type Description
matrix Matrix Matrix to set.

effect.setViewMatrix(matrix)

Set the view matrix uniform. Note: this will only work for effects that utilize the ‘View’ uniform.

Kind: instance method of Effect

Param Type Description
matrix Matrix Matrix to set.

effect.setOutline(weight, color)

Set outline params. Note: this will only work for effects that utilize the ‘OutlineWeight’ and ‘OutlineColor’ uniforms.

Kind: instance method of Effect

Param Type Description
weight Number Outline weight, range from 0.0 to 1.0.
color Color Outline color.

effect.setUvNormalizationFactor(factor)

Set a factor to normalize UV values to be 0-1. Note: this will only work for effects that utilize the ‘UvNormalizationFactor’ uniform.

Kind: instance method of Effect

Param Type Description
factor Vector2 Normalize UVs factor.

effect.setPositionsAttribute(buffer, forceSetBuffer)

Set the vertices position buffer. Only works if there’s an attribute type bound to ‘Position’.

Kind: instance method of Effect

Param Type Description
buffer WebGLBuffer Vertices position buffer.
forceSetBuffer Boolean If true, will always set buffer even if buffer is currently set.

effect.setTextureCoordsAttribute(buffer, forceSetBuffer)

Set the vertices texture coords buffer. Only works if there’s an attribute type bound to ‘TextureCoords’.

Kind: instance method of Effect

Param Type Description
buffer WebGLBuffer Vertices texture coords buffer.
forceSetBuffer Boolean If true, will always set buffer even if buffer is currently set.

effect.setColorsAttribute(buffer, forceSetBuffer)

Set the vertices colors buffer. Only works if there’s an attribute type bound to ‘Colors’.

Kind: instance method of Effect

Param Type Description
buffer WebGLBuffer Vertices colors buffer.
forceSetBuffer Boolean If true, will always set buffer even if buffer is currently set.

effect.setNormalsAttribute(buffer, forceSetBuffer)

Set the vertices normals buffer. Only works if there’s an attribute type bound to ‘Normals’.

Kind: instance method of Effect

Param Type Description
buffer WebGLBuffer Vertices normals buffer.
forceSetBuffer Boolean If true, will always set buffer even if buffer is currently set.

effect.setBinormalsAttribute(buffer, forceSetBuffer)

Set the vertices binormals buffer. Only works if there’s an attribute type bound to ‘Binormals’.

Kind: instance method of Effect

Param Type Description
buffer WebGLBuffer Vertices binormals buffer.
forceSetBuffer Boolean If true, will always set buffer even if buffer is currently set.

effect.setTangentsAttribute(buffer, forceSetBuffer)

Set the vertices tangents buffer. Only works if there’s an attribute type bound to ‘Tangents’.

Kind: instance method of Effect

Param Type Description
buffer WebGLBuffer Vertices tangents buffer.
forceSetBuffer Boolean If true, will always set buffer even if buffer is currently set.

Effect.DepthFuncs ⇒ \*

Get all supported depth funcs we can set.

Kind: static property of Effect
Returns: \* - Depth func options: {Never, Less, Equal, LessEqual, Greater, GreaterEqual, Always, NotEqual}.

MsdfFontEffect

Default effect to draw MSDF font textures.

Kind: global class

msdfFontEffect.vertexCode

Kind: instance property of MsdfFontEffect

msdfFontEffect.fragmentCode

Kind: instance property of MsdfFontEffect

msdfFontEffect.uniformTypes

Kind: instance property of MsdfFontEffect

msdfFontEffect.attributeTypes

Kind: instance property of MsdfFontEffect

ShapesEffect

Default basic effect to draw 2d shapes.

Kind: global class

shapesEffect.vertexCode

Kind: instance property of ShapesEffect

shapesEffect.fragmentCode

Kind: instance property of ShapesEffect

shapesEffect.uniformTypes

Kind: instance property of ShapesEffect

shapesEffect.attributeTypes

Kind: instance property of ShapesEffect

SpritesEffect

Default basic effect to draw 2d sprites.

Kind: global class

spritesEffect.vertexCode

Kind: instance property of SpritesEffect

spritesEffect.fragmentCode

Kind: instance property of SpritesEffect

spritesEffect.uniformTypes

Kind: instance property of SpritesEffect

spritesEffect.attributeTypes

Kind: instance property of SpritesEffect

Sprites3dEffect

Default basic effect to draw 2d sprites.

Kind: global class

sprites3dEffect.enableDepthTest

Kind: instance property of Sprites3dEffect

sprites3dEffect.enableFaceCulling

Kind: instance property of Sprites3dEffect

sprites3dEffect.vertexCode

Kind: instance property of Sprites3dEffect

sprites3dEffect.fragmentCode

Kind: instance property of Sprites3dEffect

SpritesEffectNoVertexColor

Default basic effect to draw 2d sprites without vertex color.

Kind: global class

spritesEffectNoVertexColor.vertexCode

Kind: instance property of SpritesEffectNoVertexColor

spritesEffectNoVertexColor.fragmentCode

Kind: instance property of SpritesEffectNoVertexColor

spritesEffectNoVertexColor.uniformTypes

Kind: instance property of SpritesEffectNoVertexColor

spritesEffectNoVertexColor.attributeTypes

Kind: instance property of SpritesEffectNoVertexColor

SpritesWithOutlineEffect

Default basic effect to draw 2d sprites with outline.

Kind: global class

spritesWithOutlineEffect.vertexCode

Kind: instance property of SpritesWithOutlineEffect

spritesWithOutlineEffect.fragmentCode

Kind: instance property of SpritesWithOutlineEffect

spritesWithOutlineEffect.uniformTypes

Kind: instance property of SpritesWithOutlineEffect

spritesWithOutlineEffect.attributeTypes

Kind: instance property of SpritesWithOutlineEffect

Gfx

Gfx is the graphics manager. Everything related to rendering and managing your game canvas goes here.

To access the Graphics manager you use Shaku.gfx.

Kind: global class

new Gfx()

Create the manager.

gfx.builtinEffects : Dictionary

A dictionary containing all built-in effect instances.

Kind: instance property of Gfx

gfx.defaultTextureFilter : TextureFilterModes

Default texture filter to use when no texture filter is set.

Kind: instance property of Gfx

gfx.TextureWrapModes : TextureWrapModes

Default wrap modes to use when no wrap mode is set.

Kind: instance property of Gfx

gfx.whiteTexture : TextureAsset

A 1x1 white texture.

Kind: instance property of Gfx

gfx.webglVersion ⇒ Number

Get the init WebGL version.

Kind: instance property of Gfx
Returns: Number - WebGL version number.

gfx.maxLineSegments ⇒ Number

Maximum number of vertices we allow when drawing lines.

Kind: instance property of Gfx
Returns: Number - max vertices per lines strip.

gfx.canvas ⇒ HTMLCanvasElement

Get the canvas element controlled by the gfx manager. If you didn’t provide your own canvas before initialization, you must add this canvas to your document after initializing Shaku.

Kind: instance property of Gfx
Returns: HTMLCanvasElement - Canvas we use for rendering.
Example

document.body.appendChild(Shaku.gfx.canvas);

gfx.DrawBatch

Get the draw batch base class.

Kind: instance property of Gfx
See: DrawBatch

gfx.SpriteBatch

Get the sprites batch class.

Kind: instance property of Gfx
See: SpriteBatch

gfx.SpriteBatch3D

Get the 3d sprites batch class.

Kind: instance property of Gfx
See: SpriteBatch3D

gfx.TextSpriteBatch

Get the text sprites batch class.

Kind: instance property of Gfx
See: TextSpriteBatch

gfx.ShapesBatch

Get the shapes batch class.

Kind: instance property of Gfx
See: ShapesBatch

gfx.LinesBatch

Get the lines batch class.

Kind: instance property of Gfx
See: LinesBatch

gfx.Effect

Get the Effect base class, which is required to implement custom effects.

Kind: instance property of Gfx
See: Effect

gfx.SpritesEffect

Get the default sprites effect class.

Kind: instance property of Gfx
See: SpritesEffect

gfx.SpritesEffectNoVertexColor

Get the default sprites effect class that is used when vertex colors is disabled.

Kind: instance property of Gfx
See: SpritesEffectNoVertexColor

gfx.ShapesEffect

Get the default shapes effect class that is used to draw 2d shapes.

Kind: instance property of Gfx
See: ShapesEffect

gfx.Sprites3dEffect

Get the default 3d sprites effect class that is used to draw 3d textured quads.

Kind: instance property of Gfx
See: Sprites3dEffect

gfx.MsdfFontEffect

Get the Effect for rendering fonts with an MSDF texture.

Kind: instance property of Gfx
See: MsdfFontEffect

gfx.Sprite

Get the sprite class.

Kind: instance property of Gfx
See: Sprite

gfx.SpritesGroup

Get the sprites group object.

Kind: instance property of Gfx
See: SpritesGroup

gfx.Matrix

Get the matrix object.

Kind: instance property of Gfx
See: Matrix

gfx.Vertex

Get the vertex object.

Kind: instance property of Gfx
See: Vertex

gfx.TextAlignments

Get the text alignments options.

Kind: instance property of Gfx
See: TextAlignments

gfx.BlendModes

Get the blend modes enum.

Blend Modes

Kind: instance property of Gfx
See: BlendModes

gfx.TextureWrapModes

Get the wrap modes enum.

Wrap Modes

Kind: instance property of Gfx
See: TextureWrapModes

gfx.TextureFilterModes

Get texture filter modes.

Filter Modes

Kind: instance property of Gfx
See: TextureFilterModes

gfx.drawCallsCount ⇒ Number

Get number of actual WebGL draw calls we performed since the beginning of the frame.

Kind: instance property of Gfx
Returns: Number - Number of WebGL draw calls this frame.

gfx.quadsDrawCount ⇒ Number

Get number of textured / colored quads we drawn since the beginning of the frame.

Kind: instance property of Gfx
Returns: Number - Number of quads drawn in this frame.

gfx.shapePolygonsDrawCount ⇒ Number

Get number of shape polygons we drawn since the beginning of the frame.

Kind: instance property of Gfx
Returns: Number - Number of shape polygons drawn in this frame.

gfx.setContextAttributes(flags)

Set WebGL init flags (passed as additional params to the getContext() call). You must call this before initializing Shaku.

By default, Shaku will init WebGL context with the following flags:

Kind: instance method of Gfx

Param Type Description
flags Dictionary WebGL init flags to set.

Example

Shaku.gfx.setContextAttributes({ antialias: true, alpha: false });

gfx.setCanvas(element)

Set the canvas element to initialize on. You must call this before initializing Shaku. Calling this will prevent Shaku from creating its own canvas.

Kind: instance method of Gfx

Param Type Description
element HTMLCanvasElement Canvas element to initialize on.

Example

Shaku.gfx.setCanvas(document.getElementById('my-canvas')); 

gfx.createCamera(withViewport) ⇒ Camera

Create and return a new camera instance.

Kind: instance method of Gfx
Returns: Camera - New camera object.

Param Type Description
withViewport Boolean If true, will create camera with viewport value equal to canvas’ size.

gfx.createCamera3D(withViewport) ⇒ Camera3D

Create and return a new 3D camera instance.

Kind: instance method of Gfx
Returns: Camera3D - New camera object.

Param Type Description
withViewport Boolean If true, will create camera with viewport value equal to canvas’ size.

gfx.setCameraOrthographic(offset) ⇒ Camera

Set default orthographic camera from offset.

Kind: instance method of Gfx
Returns: Camera - Camera instance.

Param Type Description
offset Vector2 Camera top-left corner.

gfx.maximizeCanvasSize([limitToParent], [allowOddNumbers])

Set resolution and canvas to the max size of its parent element or screen. If the canvas is directly under document body, it will take the max size of the page.

Kind: instance method of Gfx

Param Type Description
[limitToParent] Boolean if true, will use parent element size. If false, will stretch on entire document.
[allowOddNumbers] Boolean if true, will permit odd numbers, which could lead to small artefacts when drawing pixel art. If false (default) will round to even numbers.

gfx.setRenderTarget(texture, [keepCamera])

Set a render target (texture) to render on.

Kind: instance method of Gfx

Param Type Description
texture TextureAsset | Array.<TextureAsset> | null Render target texture to set as render target, or null to reset and render back on canvas. Can also be array for multiple targets, which will take layouts 0-15 by their order.
[keepCamera] Boolean If true, will keep current camera settings. If false (default) will reset camera.

Example

// create render target
let renderTarget = await Shaku.assets.createRenderTarget('_my_render_target', 800, 600);

// use render target
Shaku.gfx.setRenderTarget(renderTarget);
// .. draw some stuff here

// reset render target and present it on screen
// note the negative height - render targets end up with flipped Y axis
Shaku.gfx.setRenderTarget(null);
Shaku.gfx.draw(renderTarget, new Shaku.utils.Vector2(screenX / 2, screenY / 2), new Shaku.utils.Vector2(screenX, -screenY));

gfx.setResolution(width, height, updateCanvasStyle)

Set resolution and canvas size.

Kind: instance method of Gfx

Param Type Description
width Number Resolution width.
height Number Resolution height.
updateCanvasStyle Boolean If true, will also update the canvas css size in pixels.

Example

// set resolution and size of 800x600.
Shaku.gfx.setResolution(800, 600, true);

gfx.resetCamera()

Reset camera properties to default camera.

Kind: instance method of Gfx

gfx.applyCamera(camera)

Set viewport, projection and other properties from a camera instance. Changing the camera properties after calling this method will not update the renderer, until you call applyCamera again.

Kind: instance method of Gfx

Param Type Description
camera Camera Camera to apply.

gfx.getRenderingRegion(includeOffset) ⇒ Rectangle

Get current rendering region.

Kind: instance method of Gfx
Returns: Rectangle - Rectangle with rendering region.

Param Type Description
includeOffset Boolean If true (default) will include viewport offset, if exists.

gfx.getRenderingSize() ⇒ Vector2

Get current rendering size. Unlike ‘canvasSize’, this takes viewport and render target into consideration.

Kind: instance method of Gfx
Returns: Vector2 - rendering size.

gfx.getCanvasSize() ⇒ Vector2

Get canvas size as vector.

Kind: instance method of Gfx
Returns: Vector2 - Canvas size.

gfx.buildText(fontTexture, text, [fontSize], color, [alignment], [offset], [marginFactor]) ⇒ SpritesGroup

Generate a sprites group to render a string using a font texture. Take the result of this method and use with gfx.drawGroup() to render the text. This is what you use when you want to draw texts with Shaku. Note: its best to always draw texts with batching enabled.

Kind: instance method of Gfx
Returns: SpritesGroup - Sprites group containing the needed sprites to draw the given text with its properties.

Param Type Description
fontTexture FontTextureAsset Font texture asset to use.
text String Text to generate sprites for.
[fontSize] Number Font size, or undefined to use font texture base size.
color Color | Array.<Color>= Text sprites color. If array is set, will assign each color to different vertex, starting from top-left.
[alignment] TextAlignment Text alignment.
[offset] Vector2 Optional starting offset.
[marginFactor] Vector2 Optional factor for characters and line spacing. For example value of 2,1 will make double horizontal spacing.

Example

// load font texture
let fontTexture = await Shaku.assets.loadFontTexture('assets/DejaVuSansMono.ttf', {fontName: 'DejaVuSansMono'});

// generate 'hello world!' text (note: you don't have to regenerate every frame if text didn't change)
let text1 = Shaku.gfx.buildText(fontTexture, "Hello World!");
text1.position.set(40, 40);

// draw text
Shaku.gfx.drawGroup(text1, true);

gfx.centerCanvas()

Make the renderer canvas centered.

Kind: instance method of Gfx

gfx.inScreen(shape) ⇒ Boolean

Check if a given shape is currently in screen bounds, not taking camera into consideration.

Kind: instance method of Gfx
Returns: Boolean - True if given shape is in visible region.

Param Type Description
shape Circle | Vector | Rectangle | Line Shape to check.

gfx.centerCamera(position, useCanvasSize)

Make a given vector the center of the camera.

Kind: instance method of Gfx

Param Type Description
position Vector2 Camera position.
useCanvasSize Boolean If true, will always use cancas size when calculating center. If false and render target is set, will use render target’s size.

gfx.clear([color])

Clear screen to a given color.

Kind: instance method of Gfx

Param Type Description
[color] Color Color to clear screen to, or black if not set.

Example

Shaku.gfx.clear(Shaku.utils.Color.cornflowerblue);

gfx.clearDepth([value])

Clear depth buffer. Only relevant when depth is used.

Kind: instance method of Gfx

Param Type Description
[value] Number Value to clear depth buffer to.

Sprite

Sprite class.

Kind: global class

new Sprite(texture, [sourceRectangle])

Create the sprite object.

Param Type Description
texture TextureAssetBase Sprite texture.
[sourceRectangle] Rectangle Optional source rectangle.

sprite.texture : TextureAssetBase

Sprite’s texture.

Kind: instance property of Sprite

sprite.position : Vector2 | Vector3

Sprite position. If Vector3 is provided, the z value will be passed to vertices position in shader code.

Kind: instance property of Sprite

sprite.size : Vector2 | Vector3

Sprite size. If Vector3 is provided, the z value will be passed to the bottom vertices position in shader code, as position.z + size.z.

Kind: instance property of Sprite

sprite.sourceRectangle : Rectangle

Sprite source rectangle in texture. Null will take entire texture.

Kind: instance property of Sprite

sprite.rotation : Number

Sprite rotation in radians.

Kind: instance property of Sprite

sprite.origin : Vector2

Sprite origin point.

Kind: instance property of Sprite

sprite.skew : Vector2

Skew the sprite corners on X and Y axis, around the origin point.

Kind: instance property of Sprite

sprite.color : Color | Array.<Color>

Sprite color. If array is set, will assign each color to different vertex, starting from top-left.

Kind: instance property of Sprite

sprite.flipX ⇒ Boolean

Check if this sprite is flipped around X axis. This is just a sugarcoat that returns if size.x < 0.

Kind: instance property of Sprite
Returns: Boolean - If sprite is flipped on X axis.

sprite.flipX

Flip sprite around X axis. This is just a sugarcoat that set size.x to negative or positive value, without changing its scale.

Kind: instance property of Sprite

Param Type Description
flip Boolean Should we flip the sprite around X axis. If undefined, will take the negative of flipX current value, ie will toggle flipping.

sprite.flipY ⇒ Boolean

Check if this sprite is flipped around y axis. This is just a sugarcoat that returns if size.y < 0.

Kind: instance property of Sprite
Returns: Boolean - If sprite is flipped on Y axis.

sprite.flipY

Flip sprite around Y axis. This is just a sugarcoat that set size.y to negative or positive value, without changing its scale.

Kind: instance property of Sprite

Param Type Description
flip Boolean Should we flip the sprite around Y axis. If undefined, will take the negative of flipY current value, ie will toggle flipping.

sprite.setToSourceRectangleSize() ⇒ Sprite

Set size to source rectangle size.

Kind: instance method of Sprite
Returns: Sprite - this.

sprite.setToTextureSize() ⇒ Sprite

Set size to texture size.

Kind: instance method of Sprite
Returns: Sprite - this.

sprite.setSourceFromSpritesheet(texture, index, spritesCount, [margin], [setSize])

Set the source Rectangle automatically from spritesheet. This method get sprite index in sheet and how many sprites there are in total, and calculate the desired offset and size in source Rectangle based on it + source image size.

Kind: instance method of Sprite

Param Type Description
texture TextureAssetBase Texture to set source rectangle from.
index Vector2 Sprite index in spritesheet.
spritesCount Vector2 How many sprites there are in spritesheet in total.
[margin] Number How many pixels to trim from the tile (default is 0).
[setSize] Boolean If true will also set width and height based on source rectangle (default is true).

sprite.clone() ⇒ Sprite

Clone this sprite.

Kind: instance method of Sprite
Returns: Sprite - cloned sprite.

Sprite.build(texture, position, size, sourceRectangle, color, [rotation], [origin], [skew]) ⇒ Sprite

Build a sprite from params.

Kind: static method of Sprite
Returns: Sprite - New sprite instance.

Param Type Description
texture TextureAssetBase Sprite texture.
position Vector2 | Vector3 Drawing position (at origin). If vector3 is provided, will pass z value to the shader code position attribute.
size Vector2 | Vector3 | Number Drawing size. If vector3 is provided, will pass z value to the shader code position attribute for the bottom vertices, as position.z + size.z.
sourceRectangle Rectangle Source rectangle, or undefined to use the entire texture.
color Color | Array.<Color> | undefined Tint color, or undefined to not change color. If array is set, will assign each color to different vertex, starting from top-left.
[rotation] Number Rotate sprite.
[origin] Vector2 Drawing origin. This will be the point at ‘position’ and rotation origin.
[skew] Vector2 Skew the drawing corners on X and Y axis, around the origin point.

SpritesGroup

Sprites group class. This object is a container to hold sprites collection + parent transformations. You need SpritesGroup to use batched rendering.

Kind: global class

new SpritesGroup()

Create the group object.

spritesGroup.count ⇒ Number

Sprites count in group.

Kind: instance property of SpritesGroup
Returns: Number - Number of sprites in group.

spritesGroup.forEach(callback)

Iterate all sprites.

Kind: instance method of SpritesGroup

Param Type Description
callback function Callback to run on all sprites in group.

spritesGroup.setColor(color)

Set color for all sprites in group.

Kind: instance method of SpritesGroup

Param Type Description
color Color Color to set.

spritesGroup.getTransform() ⇒ Matrix

Get group’s transformations.

Kind: instance method of SpritesGroup
Returns: Matrix - Transformations matrix, or null if there’s nothing to apply.

spritesGroup.add(sprite) ⇒ Sprite

Adds a sprite to group.

Kind: instance method of SpritesGroup
Returns: Sprite - The newly added sprite.

Param Type Description
sprite Sprite Sprite to add.

spritesGroup.remove(sprite)

Remove a sprite from group.

Kind: instance method of SpritesGroup

Param Type Description
sprite Sprite Sprite to remove.

spritesGroup.shift() ⇒ Sprite

Shift first sprite element.

Kind: instance method of SpritesGroup
Returns: Sprite - The removed sprite.

spritesGroup.sort(compare)

Sort sprites.

Kind: instance method of SpritesGroup

Param Type Description
compare function Comparer method.

Vertex

A vertex we can push to sprite batch.

Kind: global class

new Vertex(position, textureCoord, color, normal)

Create the vertex data.

Param Type Description
position Vector2 | Vector3 Vertex position.
textureCoord Vector2 Vertex texture coord (in pixels).
color Color Vertex color (undefined will default to white).
normal Vector3 Vertex normal.

vertex.setPosition(position, useRef) ⇒ Vertex

Set position.

Kind: instance method of Vertex
Returns: Vertex - this.

Param Type Description
position Vector2 | Vector3 Vertex position.
useRef Boolean If true, will not clone the given position vector and use its reference instead.

vertex.setTextureCoords(textureCoord, useRef) ⇒ Vertex

Set texture coordinates.

Kind: instance method of Vertex
Returns: Vertex - this.

Param Type Description
textureCoord Vector2 Vertex texture coord (in pixels).
useRef Boolean If true, will not clone the given coords vector and use its reference instead.

vertex.setColor(color, useRef) ⇒ Vertex

Set vertex color.

Kind: instance method of Vertex
Returns: Vertex - this.

Param Type Description
color Color Vertex color.
useRef Boolean If true, will not clone the given color and use its reference instead.

vertex.setNormal(normal, useRef) ⇒ Vertex

Set vertex normal.

Kind: instance method of Vertex
Returns: Vertex - this.

Param Type Description
normal Vector3 Vertex normal.
useRef Boolean If true, will not clone the given normal and use its reference instead.

vertex.setBinormal(binormal, useRef) ⇒ Vertex

Set vertex binormal.

Kind: instance method of Vertex
Returns: Vertex - this.

Param Type Description
binormal Vector3 Vertex binormal.
useRef Boolean If true, will not clone the given binormal and use its reference instead.

vertex.setTangent(tangent, useRef) ⇒ Vertex

Set vertex tangent.

Kind: instance method of Vertex
Returns: Vertex - this.

Param Type Description
tangent Vector3 Vertex tangent.
useRef Boolean If true, will not clone the given tangent and use its reference instead.

Gamepad

Gamepad data object. This object represents a snapshot of a gamepad state, it does not update automatically.

Kind: global class

new Gamepad(gp)

Create gamepad state object.

Param Type Description
gp \* Browser gamepad state object.

gamepad.id : String

Gamepad Id.

Kind: instance property of Gamepad

gamepad.axis1 : Vector2

Gamepad first axis value.

Kind: instance property of Gamepad

gamepad.axis2 : Vector2

Gamepad second axis value.

Kind: instance property of Gamepad

gamepad.mapping : String

Mapping type.

Kind: instance property of Gamepad

gamepad.isMapped : Boolean

True if the gamepad is of a known type and we have extra mapped attributes. False if unknown / not supported.

Kind: instance property of Gamepad

gamepad.leftStick : Vector2

Gamepad left stick. Only available with “standard” mapping.

Kind: instance property of Gamepad

gamepad.rightStick : Vector2

Gamepad right stick. Only available with “standard” mapping.

Kind: instance property of Gamepad

gamepad.leftStickPressed : Boolean

Gamepad left stick is pressed. Only available with “standard” mapping.

Kind: instance property of Gamepad

gamepad.leftStickPressed : Boolean

Gamepad right stick is pressed. Only available with “standard” mapping.

Kind: instance property of Gamepad

gamepad.rightButtons : FourButtonsCluster

Right cluster button states.

Kind: instance property of Gamepad

gamepad.leftButtons : FourButtonsCluster

Left cluster button states.

Kind: instance property of Gamepad

gamepad.leftButtons : FourButtonsCluster

Center cluster button states.

Kind: instance property of Gamepad

gamepad.frontButtons : FrontButtons

Front buttons states.

Kind: instance property of Gamepad

gamepad.isMapped : Boolean

True if the gamepad is of a known type and we have extra mapped attributes. False if unknown.

Kind: instance property of Gamepad

gamepad.buttonsCount ⇒ Number

Get buttons count.

Kind: instance property of Gamepad
Returns: Number - Buttons count.

gamepad.button(index) ⇒ Boolean

Get button state (if pressed down) by index.

Kind: instance method of Gamepad
Returns: Boolean - True if pressed, false otherwise.

Param Type Description
index Number Button index to check.

FourButtonsCluster

Buttons cluster container - 4 buttons.

Kind: global class

new FourButtonsCluster(bottom, right, left, top)

Create the cluster states.

Param Type Description
bottom Boolean Bottom button state.
right Boolean Right button state.
left Boolean Left button state.
top Boolean Top button state.

ThreeButtonsCluster

Buttons cluster container - 3 buttons.

Kind: global class

new ThreeButtonsCluster(left, right, center)

Create the cluster states.

Param Type Description
left Boolean Left button state.
right Boolean Right button state.
center Boolean Center button state.

FrontButtons

Front buttons.

Kind: global class

new FrontButtons()

Create the cluster states.

Input

Input manager. Used to recieve input from keyboard and mouse.

To access the Input manager use Shaku.input.

Kind: global class

new Input()

Create the manager.

input.preventDefaults : Boolean

If true, will prevent default input events by calling preventDefault().

Kind: instance property of Input

input.disableMouseWheelAutomaticScrolling : Boolean

By default, when holding wheel button down browsers will turn into special page scroll mode and will not emit mouse move events. if this property is set to true (default), the Input manager will prevent this behavior, so we could still get mouse delta while mouse wheel is held down.

Kind: instance property of Input

input.disableContextMenu : Boolean

If true (default), will disable the context menu (what typically opens when you right click the page).

Kind: instance property of Input

input.delegateTouchInputToMouse : Boolean

If true (default), will treat touch events (touch start / touch end / touch move) as if the user clicked and moved a mouse.

Kind: instance property of Input

input.delegateGamepadInputToKeys : Boolean

If true (default), will delegate events from mapped gamepads to custom keys. This will add the following codes to all basic query methods (down, pressed, released, doublePressed, doubleReleased):

Kind: instance property of Input

input.resetOnFocusLoss : Boolean

If true (default), will reset all states if the window loses focus.

Kind: instance property of Input

input.defaultDoublePressInterval : Number

Default time, in milliseconds, to consider two consecutive key presses as a double-press.

Kind: instance property of Input

input.MouseButtons

Get the Mouse Buttons enum.

Kind: instance property of Input
See: MouseButtons

input.KeyboardKeys

Get the Keyboard Buttons enum.

Kind: instance property of Input
See: KeyboardKeys

input.TouchKeyCode ⇒ String

Return the string code to use in order to get touch events.

Kind: instance property of Input
Returns: String - Key code to use for touch events.

input.touchPosition ⇒ Vector2

Get touch screen touching position. Note: if not currently touching, will return last known position.

Kind: instance property of Input
Returns: Vector2 - Touch position.

input.touching ⇒ Boolean

Get if currently touching a touch screen.

Kind: instance property of Input
Returns: Boolean - True if currently touching the screen.

input.touchStarted ⇒ Boolean

Get if started touching a touch screen in current frame.

Kind: instance property of Input
Returns: Boolean - True if started touching the screen now.

input.touchEnded ⇒ Boolean

Get if stopped touching a touch screen in current frame.

Kind: instance property of Input
Returns: Boolean - True if stopped touching the screen now.

input.mousePosition ⇒ Vector2

Get mouse position.

Kind: instance property of Input
Returns: Vector2 - Mouse position.

input.prevMousePosition ⇒ Vector2

Get mouse previous position (before the last endFrame() call).

Kind: instance property of Input
Returns: Vector2 - Mouse position in previous frame.

input.mouseDelta ⇒ Vector2

Get mouse movement since last endFrame() call.

Kind: instance property of Input
Returns: Vector2 - Mouse change since last frame.

input.mouseMoving ⇒ Boolean

Get if mouse is currently moving.

Kind: instance property of Input
Returns: Boolean - True if mouse moved since last frame, false otherwise.

input.shiftDown ⇒ Boolean

Get if any of the shift keys are currently down.

Kind: instance property of Input
Returns: Boolean - True if there’s a shift key pressed down.

input.ctrlDown ⇒ Boolean

Get if any of the Ctrl keys are currently down.

Kind: instance property of Input
Returns: Boolean - True if there’s a Ctrl key pressed down.

input.altDown ⇒ Boolean

Get if any of the Alt keys are currently down.

Kind: instance property of Input
Returns: Boolean - True if there’s an Alt key pressed down.

input.anyKeyPressed ⇒ Boolean

Get if any keyboard key was pressed this frame.

Kind: instance property of Input
Returns: Boolean - True if any key was pressed down this frame.

input.anyKeyDown ⇒ Boolean

Get if any keyboard key is currently down.

Kind: instance property of Input
Returns: Boolean - True if there’s a key pressed down.

input.anyMouseButtonPressed ⇒ Boolean

Get if any mouse button was pressed this frame.

Kind: instance property of Input
Returns: Boolean - True if any of the mouse buttons were pressed this frame.

input.anyMouseButtonDown ⇒ Boolean

Get if any mouse button is down.

Kind: instance property of Input
Returns: Boolean - True if any of the mouse buttons are pressed.

input.mouseWheelSign ⇒ Number

Get mouse wheel sign.

Kind: instance property of Input
Returns: Number - Mouse wheel sign (-1 or 1) for wheel scrolling that happened during this frame. Will return 0 if mouse wheel is not currently being used.

input.mouseWheel ⇒ Number

Get mouse wheel value.

Kind: instance property of Input
Returns: Number - Mouse wheel value.

input.setTargetElement(element)

Set the target element to attach input to. If not called, will just use the entire document. Must be called before initializing Shaku. This can also be a method to invoke while initializing.

Kind: instance method of Input

Param Type Description
element Element | elementCallback Element to attach input to.

Example

// the following will use whatever canvas the gfx manager uses as input element.
// this means mouse offset will also be relative to this element.
Shaku.input.setTargetElement(() => Shaku.gfx.canvas);

input.gamepad([index]) ⇒ Gamepad

Get Gamepad current states, or null if not connected. Note: this object does not update itself, you’ll need to query it again every frame.

Kind: instance method of Input
Returns: Gamepad - Gamepad current state.

Param Type Description
[index] Number Gamepad index or undefined for first connected device.

input.gamepadId([index]) ⇒

Get gamepad id, or null if not connected to this slot.

Kind: instance method of Input
Returns: Gamepad id or null.

Param Type Description
[index] Number Gamepad index or undefined for first connected device.

input.gamepadIds() ⇒ Array.<String>

Return a list with connected devices ids.

Kind: instance method of Input
Returns: Array.<String> - List of connected devices ids.

input.setCustomState(code, value)

Set a custom key code state you can later use with all the built in methods (down / pressed / released / doublePressed, etc.) For example, lets say you want to implement a simulated keyboard and use it alongside the real keyboard. When your simulated keyboard space key is pressed, you can call setCustomState('sim_space', true). When released, call setCustomState('sim_space', false). Now you can use Shaku.input.down(['space', 'sim_space']) to check if either a real space or simulated space is pressed down.

Kind: instance method of Input

Param Type Description
code String Code to set state for.
value Boolean | null Current value to set, or null to remove custom key.

input.mousePressed(button) ⇒ Boolean

Get if mouse button was pressed this frame.

Kind: instance method of Input
Returns: Boolean - True if mouse button is currently down, but was up in previous frame.

Param Type Default Description
button MouseButton 0 Button code (defults to MouseButtons.left).

input.mouseDown(button) ⇒ Boolean

Get if mouse button is currently pressed.

Kind: instance method of Input
Returns: Boolean - true if mouse button is currently down, false otherwise.

Param Type Default Description
button MouseButton 0 Button code (defults to MouseButtons.left).

input.mouseUp(button) ⇒ Boolean

Get if mouse button is currently not down.

Kind: instance method of Input
Returns: Boolean - true if mouse button is currently up, false otherwise.

Param Type Default Description
button MouseButton 0 Button code (defults to MouseButtons.left).

input.mouseReleased(button) ⇒ Boolean

Get if mouse button was released in current frame.

Kind: instance method of Input
Returns: Boolean - True if mouse was down last frame, but released in current frame.

Param Type Default Description
button MouseButton 0 Button code (defults to MouseButtons.left).

input.keyDown(key) ⇒ boolean

Get if keyboard key is currently pressed down.

Kind: instance method of Input
Returns: boolean - True if keyboard key is currently down, false otherwise.

Param Type Description
key KeyboardKey Keyboard key code.

input.keyUp(key) ⇒ Boolean

Get if keyboard key is currently not down.

Kind: instance method of Input
Returns: Boolean - True if keyboard key is currently up, false otherwise.

Param Type Description
key KeyboardKey Keyboard key code.

input.keyReleased(button) ⇒ Boolean

Get if a keyboard button was released in current frame.

Kind: instance method of Input
Returns: Boolean - True if key was down last frame, but released in current frame.

Param Type Description
button KeyboardKey Keyboard key code.

input.keyPressed(key) ⇒ Boolean

Get if keyboard key was pressed this frame.

Kind: instance method of Input
Returns: Boolean - True if key is currently down, but was up in previous frame.

Param Type Description
key KeyboardKey Keyboard key code.

input.down(code) ⇒ Boolean

Return if a mouse or keyboard button is currently down.

Kind: instance method of Input
Returns: Boolean - True if key or mouse button are down.

Param Type Description
code string | Array.<String> Keyboard, touch or mouse code. Can be array of codes to test any of them. For mouse buttons: set code to ‘mouse_left’, ‘mouse_right’ or ‘mouse_middle’. For keyboard buttons: use one of the keys of KeyboardKeys (for example ‘a’, ‘alt’, ‘up_arrow’, etc..). For touch screen: set code to ‘touch’. For numbers (0-9): you can use the number itself. Note: if you inject any custom state via setCustomState(), you can use its code here too.

Example

if (Shaku.input.down(['mouse_left', 'touch', 'space'])) { alert('mouse, touch screen or space are pressed!'); }

input.released(code) ⇒ Boolean

Return if a mouse or keyboard button was released in this frame.

Kind: instance method of Input
Returns: Boolean - True if key or mouse button were down in previous frame, and released this frame.

Param Type Description
code string | Array.<String> Keyboard, touch, gamepad or mouse button code. Can be array of codes to test any of them. For mouse buttons: set code to ‘mouse_left’, ‘mouse_right’ or ‘mouse_middle’. For keyboard buttons: use one of the keys of KeyboardKeys (for example ‘a’, ‘alt’, ‘up_arrow’, etc..). For touch screen: set code to ‘touch’. For numbers (0-9): you can use the number itself. Note: if you inject any custom state via setCustomState(), you can use its code here too.

Example

if (Shaku.input.released(['mouse_left', 'touch', 'space'])) { alert('mouse, touch screen or space were released!'); }

input.pressed(code) ⇒ Boolean

Return if a mouse or keyboard button was pressed in this frame.

Kind: instance method of Input
Returns: Boolean - True if key or mouse button where up in previous frame, and pressed this frame.

Param Type Description
code string | Array.<String> Keyboard, touch, gamepad or mouse button code. Can be array of codes to test any of them. For mouse buttons: set code to ‘mouse_left’, ‘mouse_right’ or ‘mouse_middle’. For keyboard buttons: use one of the keys of KeyboardKeys (for example ‘a’, ‘alt’, ‘up_arrow’, etc..). For touch screen: set code to ‘touch’. For numbers (0-9): you can use the number itself. Note: if you inject any custom state via setCustomState(), you can use its code here too.

Example

if (Shaku.input.pressed(['mouse_left', 'touch', 'space'])) { alert('mouse, touch screen or space were pressed!'); }

input.lastReleaseTime(code) ⇒ Number

Return timestamp, in milliseconds, of the last time this key code was released.

Kind: instance method of Input
Returns: Number - Timestamp of last key release, or 0 if was never released.

Param Type Description
code string Keyboard, touch, gamepad or mouse button code. For mouse buttons: set code to ‘mouse_left’, ‘mouse_right’ or ‘mouse_middle’. For keyboard buttons: use one of the keys of KeyboardKeys (for example ‘a’, ‘alt’, ‘up_arrow’, etc..). For touch screen: set code to ‘touch’. For numbers (0-9): you can use the number itself. Note: if you inject any custom state via setCustomState(), you can use its code here too.

Example

let lastReleaseTime = Shaku.input.lastReleaseTime('mouse_left');

input.lastPressTime(code) ⇒ Number

Return timestamp, in milliseconds, of the last time this key code was pressed.

Kind: instance method of Input
Returns: Number - Timestamp of last key press, or 0 if was never pressed.

Param Type Description
code string Keyboard, touch, gamepad or mouse button code. For mouse buttons: set code to ‘mouse_left’, ‘mouse_right’ or ‘mouse_middle’. For keyboard buttons: use one of the keys of KeyboardKeys (for example ‘a’, ‘alt’, ‘up_arrow’, etc..). For touch screen: set code to ‘touch’. For numbers (0-9): you can use the number itself. Note: if you inject any custom state via setCustomState(), you can use its code here too.

Example

let lastPressTime = Shaku.input.lastPressTime('mouse_left');

input.doublePressed(code, maxInterval) ⇒ Boolean

Return if a key was double-pressed.

Kind: instance method of Input
Returns: Boolean - True if one or more key codes double-pressed, false otherwise.

Param Type Description
code string | Array.<string> Keyboard, touch, gamepad or mouse button code. Can be array of codes to test any of them. For mouse buttons: set code to ‘mouse_left’, ‘mouse_right’ or ‘mouse_middle’. For keyboard buttons: use one of the keys of KeyboardKeys (for example ‘a’, ‘alt’, ‘up_arrow’, etc..). For touch screen: set code to ‘touch’. For numbers (0-9): you can use the number itself. Note: if you inject any custom state via setCustomState(), you can use its code here too.
maxInterval Number Max interval time, in milliseconds, to consider it a double-press. Defaults to defaultDoublePressInterval.

Example

let doublePressed = Shaku.input.doublePressed(['mouse_left', 'touch', 'space']);

input.doubleReleased(code, maxInterval) ⇒ Boolean

Return if a key was double-released.

Kind: instance method of Input
Returns: Boolean - True if one or more key codes double-released, false otherwise.

Param Type Description
code string | Array.<string> Keyboard, touch, gamepad or mouse button code. Can be array of codes to test any of them. For mouse buttons: set code to ‘mouse_left’, ‘mouse_right’ or ‘mouse_middle’. For keyboard buttons: use one of the keys of KeyboardKeys (for example ‘a’, ‘alt’, ‘up_arrow’, etc..). For touch screen: set code to ‘touch’. For numbers (0-9): you can use the number itself. Note: if you inject any custom state via setCustomState(), you can use its code here too.
maxInterval Number Max interval time, in milliseconds, to consider it a double-release. Defaults to defaultDoublePressInterval.

Example

let doubleReleased = Shaku.input.doubleReleased(['mouse_left', 'touch', 'space']);

Logger

A logger manager. By default writes logs to console.

Kind: global class

logger.trace(msg)

Write a trace level log message.

Kind: instance method of Logger

Param Type Description
msg String Message to write.

logger.debug(msg)

Write a debug level log message.

Kind: instance method of Logger

Param Type Description
msg String Message to write.

logger.info(msg)

Write an info level log message.

Kind: instance method of Logger

Param Type Description
msg String Message to write.

logger.warn(msg)

Write a warning level log message.

Kind: instance method of Logger

Param Type Description
msg String Message to write.

logger.error(msg)

Write an error level log message.

Kind: instance method of Logger

Param Type Description
msg String Message to write.

logger.throwErrorOnWarnings(enable)

Set logger to throw an error every time a log message with severity higher than warning is written.

Kind: instance method of Logger

Param Type Description
enable Boolean Set to true to throw error on warnings.

IManager

Interface for any manager. Manager = manages a domain in Shaku, such as gfx (graphics), sfx (sounds), input, etc.

Kind: global class

iManager.setup() ⇒ Promise

Initialize the manager.

Kind: instance method of IManager
Returns: Promise - Promise to resolve when initialization is done.

iManager.startFrame()

Called every update at the begining of the frame.

Kind: instance method of IManager

iManager.endFrame()

Called every update at the end of the frame.

Kind: instance method of IManager

iManager.destroy()

Destroy the manager.

Kind: instance method of IManager

Sfx

Sfx manager. Used to play sound effects and music.

To access the Sfx manager use Shaku.sfx.

Kind: global class

new Sfx()

Create the manager.

sfx.SoundMixer

Get the SoundMixer class.

Kind: instance property of Sfx
See: SoundMixer

sfx.playingSoundsCount ⇒ Number

Get currently playing sounds count.

Kind: instance property of Sfx
Returns: Number - Number of sounds currently playing.

sfx.masterVolume ⇒ Number

Get master volume. This affect all sound effects volumes.

Kind: instance property of Sfx
Returns: Number - Current master volume value.

sfx.masterVolume

Set master volume. This affect all sound effects volumes.

Kind: instance property of Sfx

Param Type Description
value Number Master volume to set.

sfx.play(soundAsset, volume, playbackRate, preservesPitch) ⇒ Promise

Play a sound once without any special properties and without returning a sound instance. Its a more convinient method to play sounds, but less efficient than ‘createSound()’ if you want to play multiple times.

Kind: instance method of Sfx
Returns: Promise - Promise to resolve when sound starts playing.

Param Type Description
soundAsset SoundAsset Sound asset to play.
volume Number Volume to play sound (default to max).
playbackRate Number Optional playback rate factor.
preservesPitch Boolean Optional preserve pitch when changing rate factor.

Example

let sound = await Shaku.assets.loadSound("assets/my_sound.ogg");
Shaku.sfx.play(sound, 0.75);

sfx.stopAll()

Stop all playing sounds.

Kind: instance method of Sfx
Example

Shaku.sfx.stopAll();

sfx.createSound(sound) ⇒ SoundInstance

Create and return a sound instance you can use to play multiple times.

Kind: instance method of Sfx
Returns: SoundInstance - Newly created sound instance.

Param Type Description
sound SoundAsset Sound asset to play.

Example

let sound = await Shaku.assets.loadSound("assets/my_sound.ogg");
let soundInstance = Shaku.sfx.createSound(sound);
soundInstance.play();

SoundInstance

A sound effect instance you can play and stop.

Kind: global class

new SoundInstance(sfxManager, url)

Create a sound instance.

Param Type Description
sfxManager Sfx Sfx manager instance.
url String Sound URL or source.

soundInstance.playbackRate ⇒ Number

Get sound effect playback rate.

Kind: instance property of SoundInstance
Returns: Number - Playback rate.

soundInstance.playbackRate

Set playback rate.

Kind: instance property of SoundInstance

Param Type Description
val Number Playback value to set.

soundInstance.preservesPitch ⇒ Boolean

Get if to preserve pitch while changing playback rate.

Kind: instance property of SoundInstance
Returns: Boolean - Preserve pitch state of the sound instance.

soundInstance.preservesPitch

Set if to preserve pitch while changing playback rate.

Kind: instance property of SoundInstance

Param Type Description
val Boolean New preserve pitch value to set.

soundInstance.loop ⇒ Boolean

Get if playing in loop.

Kind: instance property of SoundInstance
Returns: Boolean - If this sound should play in loop.

soundInstance.loop

Set if playing in loop.

Kind: instance property of SoundInstance

Param Type Description
value Boolean If this sound should play in loop.

soundInstance.volume ⇒ Number

Get volume.

Kind: instance property of SoundInstance
Returns: Number - Sound effect volume.

soundInstance.volume

Set volume.

Kind: instance property of SoundInstance

Param Type Description
value Number Sound effect volume to set.

soundInstance.currentTime ⇒ Number

Get current time in track.

Kind: instance property of SoundInstance
Returns: Number - Current time in playing sound.

soundInstance.currentTime

Set current time in track.

Kind: instance property of SoundInstance

Param Type Description
value Number Set current playing time in sound track.

soundInstance.duration ⇒ Number

Get track duration.

Kind: instance property of SoundInstance
Returns: Number - Sound duration in seconds.

soundInstance.paused ⇒ Boolean

Get if sound is currently paused.

Kind: instance property of SoundInstance
Returns: Boolean - True if sound is currently paused.

soundInstance.playing ⇒ Boolean

Get if sound is currently playing.

Kind: instance property of SoundInstance
Returns: Boolean - True if sound is currently playing.

soundInstance.finished ⇒ Boolean

Get if finished playing.

Kind: instance property of SoundInstance
Returns: Boolean - True if sound reached the end and didn’t loop.

soundInstance.disposeWhenDone()

Dispose the audio object when done playing the sound. This will call dispose() automatically when audio ends.

Kind: instance method of SoundInstance

soundInstance.dispose()

Dispose the audio object and clear its resources. When playing lots of sounds its important to call dispose on sounds you no longer use, to avoid getting hit by “Blocked attempt to create a WebMediaPlayer” exception.

Kind: instance method of SoundInstance

soundInstance.play() ⇒ Promise

Play sound.

Kind: instance method of SoundInstance
Returns: Promise - Promise to return when sound start playing.

soundInstance.pause()

Pause the sound.

Kind: instance method of SoundInstance

soundInstance.replay() ⇒ Promise

Replay sound from start.

Kind: instance method of SoundInstance
Returns: Promise - Promise to return when sound start playing.

soundInstance.stop() ⇒ Boolean

Stop the sound and go back to start.

Kind: instance method of SoundInstance
Returns: Boolean - True if successfully stopped sound, false otherwise.

SoundMixer

A utility class to mix between two sounds.

Kind: global class

new SoundMixer(sound1, sound2, allowOverlapping)

Create the sound mixer.

Param Type Description
sound1 SoundInstance Sound to mix from. Can be null to just fade in.
sound2 SoundInstance Sound to mix to. Can be null to just fade out.
allowOverlapping Boolean If true (default), will mix while overlapping sounds. If false, will first finish first sound before begining next.

soundMixer.fromSound ⇒ SoundInstance

Get first sound.

Kind: instance property of SoundMixer
Returns: SoundInstance - First sound instance.

soundMixer.toSound ⇒ SoundInstance

Get second sound.

Kind: instance property of SoundMixer
Returns: SoundInstance - Second sound instance.

soundMixer.progress ⇒ Number

Return current progress.

Kind: instance property of SoundMixer
Returns: Number - Mix progress from 0 to 1.

soundMixer.stop()

Stop both sounds.

Kind: instance method of SoundMixer

soundMixer.updateDelta(delta)

Update the mixer progress with time delta instead of absolute value.

Kind: instance method of SoundMixer

Param Type Description
delta Number Progress delta, in seconds.

soundMixer.update(progress)

Update the mixer progress.

Kind: instance method of SoundMixer

Param Type Description
progress Number Transition progress from sound1 to sound2. Values must be between 0.0 to 1.0.

Shaku

Shaku’s main object. This object wraps the entire lib namespace, and this is what you use to access all managers and manage your main loop.

Kind: global class

new Shaku()

Create the Shaku main object.

shaku.utils : Utils

Different utilities and framework objects, like vectors, rectangles, colors, etc.

Kind: instance property of Shaku

shaku.sfx : Sfx

Sound effects and music manager.

Kind: instance property of Shaku

shaku.gfx : Gfx

Graphics manager.

Kind: instance property of Shaku

shaku.input : Input

Input manager.

Kind: instance property of Shaku

shaku.assets : Assets

Assets manager.

Kind: instance property of Shaku

shaku.collision : Collision

Collision detection manager.

Kind: instance property of Shaku

shaku.pauseWhenNotFocused : Boolean

If true, will pause the updates and drawing calls when window is not focused. Will also not update elapsed time.

Kind: instance property of Shaku

shaku.pause : Boolean

Set to true to completely pause Shaku (will skip updates, drawing, and time counting).

Kind: instance property of Shaku

shaku.pauseGameTime : Boolean

Set to true to pause just the game time. This will not pause real-life time. If you need real-life time stop please use the Python package.

Kind: instance property of Shaku

shaku.gameTime ⇒ GameTime

Get current frame game time. Only valid between startFrame() and endFrame().

Kind: instance property of Shaku
Returns: GameTime - Current frame’s gametime.

shaku.version ⇒ String

Get Shaku’s version.

Kind: instance property of Shaku
Returns: String - Shaku’s version.

shaku.init([managers]) ⇒ Promise

Method to select managers to use + initialize them.

Kind: instance method of Shaku
Returns: Promise - promise to resolve when finish initialization.

Param Type Description
[managers] Array.<IManager> Array with list of managers to use or null to use all.

shaku.destroy()

Destroy all managers

Kind: instance method of Shaku

shaku.isCurrentlyPaused() ⇒ Boolean

Get if the Shaku is currently paused, either because the ‘paused’ property is set, or because the document is not focused.

Kind: instance method of Shaku
Returns: Boolean - True if currently paused for any reason.

shaku.startFrame()

Start frame (update all managers).

Kind: instance method of Shaku

shaku.endFrame()

End frame (update all managers).

Kind: instance method of Shaku

shaku.silent()

Make Shaku run in silent mode, without logs. You can call this before init.

Kind: instance method of Shaku

shaku.throwErrorOnWarnings(enable)

Set logger to throw an error every time a log message with severity higher than warning is written. You can call this before init.

Kind: instance method of Shaku

Param Type Description
enable Boolean Set to true to throw error on warnings.

shaku.getFpsCount() ⇒ Number

Return current FPS count. Note: will return 0 until at least one second have passed.

Kind: instance method of Shaku
Returns: Number - FPS count.

shaku.getAverageFrameTime() ⇒ Number

Get how long on average it takes to complete a game frame.

Kind: instance method of Shaku
Returns: Number - Average time, in milliseconds, it takes to complete a game frame.

shaku.requestAnimationFrame(callback) ⇒ Number

Request animation frame with fallbacks.

Kind: instance method of Shaku
Returns: Number - Handle for cancellation.

Param Type Description
callback function Method to invoke in next animation frame.

shaku.cancelAnimationFrame(id)

Cancel animation frame with fallbacks.

Kind: instance method of Shaku

Param Type Description
id Number Request handle.

shaku.setLogger(loggerHandler)

Set the logger writer class (will replace the default console output).

Kind: instance method of Shaku

Param Type Description
loggerHandler \* New logger handler (must implement trace, debug, info, warn, error methods).

shaku.getLogger() ⇒ Logger

Get / create a custom logger.

Kind: instance method of Shaku
Returns: Logger - Logger instance.

Animator

Implement an animator object that change values over time using Linear Interpolation. Usage example: (new Animator(sprite)).from({‘position.x’: 0}).to({‘position.x’: 100}).duration(1).play();

Kind: global class

new Animator(target)

Create the animator.

Param Type Description
target \* Any object you want to animate.

animator.speedFactor

Speed factor to multiply with delta every time this animator updates.

Kind: instance property of Animator

animator.ended ⇒ Boolean

Get if this animator finished.

Kind: instance property of Animator
Returns: Boolean - True if animator finished.

animator.update(delta)

Update this animator with a given delta time.

Kind: instance method of Animator

Param Type Description
delta Number Delta time to progress this animator by.

animator.then(callback) ⇒ Animator

Set a method to run when animation ends.

Kind: instance method of Animator
Returns: Animator - this.

Param Type Description
callback function Callback to invoke when done.

animator.smoothDamp(enable) ⇒ Animator

Set smooth damp. If true, lerping will go slower as the animation reach its ending.

Kind: instance method of Animator
Returns: Animator - this.

Param Type Description
enable Boolean set smooth damp mode.

animator.repeats(enable, reverseAnimation) ⇒ Animator

Set if the animator should repeat itself.

Kind: instance method of Animator
Returns: Animator - this.

Param Type Description
enable Boolean | Number false to disable repeating, true for endless repeats, or a number for limited number of repeats.
reverseAnimation Boolean if true, it will reverse animation to repeat it instead of just “jumping” back to starting state.

animator.reverseBackToStart() ⇒ Animator

If true, will reverse animation back to start values after done. This is equivalent to calling repeats(1, true).

Kind: instance method of Animator
Returns: Animator - this.

animator.from(values) ⇒ Animator

Set ‘from’ values. You don’t have to provide ‘from’ values, when a value is not set the animator will just take whatever was set in target when first update is called.

Kind: instance method of Animator
Returns: Animator - this.

Param Type Description
values \* Values to set as ‘from’ values. Key = property name in target (can contain dots for nested), value = value to start animation from.

animator.to(values) ⇒ Animator

Set ‘to’ values, ie the result when animation ends.

Kind: instance method of Animator
Returns: Animator - this.

Param Type Description
values \* Values to set as ‘to’ values. Key = property name in target (can contain dots for nested), value = value to start animation from.

animator.flipFromAndTo()

Flip between the ‘from’ and the ‘to’ states.

Kind: instance method of Animator

animator.duration(seconds) ⇒ Animator

Make this Animator update automatically with the gameTime delta time. Note: this will change the speedFactor property.

Kind: instance method of Animator
Returns: Animator - this.

Param Type Description
seconds Number Animator duration time in seconds.

animator.reset() ⇒ Animator

Reset animator progress.

Kind: instance method of Animator
Returns: Animator - this.

animator.play() ⇒ Animator

Make this Animator update automatically with the gameTime delta time, until its done.

Kind: instance method of Animator
Returns: Animator - this.

Box

A 3D box shape.

Kind: global class

new Box(min, max)

Create the 3d box.

Param Type Description
min Vector3 Box min vector.
max Vector3 Box max vector.

box.set(min, max) ⇒ Box

Set the box min and max corners.

Kind: instance method of Box
Returns: Box - Self.

Param Type Description
min Vector3 Box min vector.
max Vector3 Box max vector.

box.setFromArray(array) ⇒ Box

Set box values from array.

Kind: instance method of Box
Returns: Box - Self.

Param Type Description
array Array.<Number> Array of values to load from.

box.setFromPoints(points) ⇒ Box

Set box from array of points.

Kind: instance method of Box
Returns: Box - Self.

Param Type Description
points Array.<Vector3> Points to set box from.

box.setFromCenterAndSize(center, size) ⇒ Box

Set box from center and size.

Kind: instance method of Box
Returns: Box - Self.

Param Type Description
center Vector3 Center position.
size Vector3 Box size.

box.clone() ⇒ Box

Clone this box.

Kind: instance method of Box
Returns: Box - Cloned box.

box.copy(box) ⇒ Box

Copy values from another box.

Kind: instance method of Box
Returns: Box - Self.

Param Type Description
box Box Box to copy.

box.makeEmpty() ⇒ Box

Turn this box into empty state.

Kind: instance method of Box
Returns: Box - Self.

box.isEmpty() ⇒ Boolean

Check if this box is empty.

Kind: instance method of Box
Returns: Boolean - True if empty.

box.getCenter() ⇒ Vector3

Get center position.

Kind: instance method of Box
Returns: Vector3 - Center position.

box.getSize() ⇒ Vector3

Get box size.

Kind: instance method of Box
Returns: Vector3 - Box size.

box.expandByPoint(point) ⇒ Box

Expand this box by a point. This will adjust the box boundaries to contain the point.

Kind: instance method of Box
Returns: Box - Self.

Param Type Description
point Vector3 Point to extend box by.

box.expandByVector(vector) ⇒ Box

Expand this box by pushing its boundaries by a vector. This will adjust the box boundaries by pushing them away from the center by the value of the given vector.

Kind: instance method of Box
Returns: Box - Self.

Param Type Description
vector Vector3 Vector to expand by.

box.expandByScalar(scalar) ⇒ Box

Expand this box by pushing its boundaries by a given scalar. This will adjust the box boundaries by pushing them away from the center by the value of the given scalar.

Kind: instance method of Box
Returns: Box - Self.

Param Type Description
scalar Number Value to expand by.

box.containsPoint(point) ⇒ Boolean

Check if this box contains a point.

Kind: instance method of Box
Returns: Boolean - True if box containing the point.

Param Type Description
point Vector3 Point to check.

box.containsBox(box) ⇒ Boolean

Check if this box contains another box.

Kind: instance method of Box
Returns: Boolean - True if box containing the box.

Param Type Description
box Box Box to check.

box.collideBox(box) ⇒ Boolean

Check if this box collides with another box.

Kind: instance method of Box
Returns: Boolean - True if collide, false otherwise.

Param Type Description
box Box Box to test collidion with.

box.collideSphere(sphere) ⇒ Boolean

Check if this box collides with a sphere.

Kind: instance method of Box
Returns: Boolean - True if collide, false otherwise.

Param Type Description
sphere Sphere Sphere to test collidion with.

box.collidePlane(plane) ⇒ Boolean

Check if this box collides with a plane.

Kind: instance method of Box
Returns: Boolean - True if collide, false otherwise.

Param Type Description
plane Plane Plane to test collidion with.

box.clampPoint(point) ⇒ Vector3

Clamp a given vector inside this box.

Kind: instance method of Box
Returns: Vector3 - Vector clammped.

Param Type Description
point Vector3 Vector to clamp.

box.distanceToPoint(point) ⇒ Number

Get distance between this box and a given point.

Kind: instance method of Box
Returns: Number - Distance to point.

Param Type Description
point Vector3 Point to get distance to.

box.intersectWith(box) ⇒ Box

Computes the intersection of this box with another box. This will set the upper bound of this box to the lesser of the two boxes’ upper bounds and the lower bound of this box to the greater of the two boxes’ lower bounds. If there’s no overlap, makes this box empty.

Kind: instance method of Box
Returns: Box - Self.

Param Type Description
box Box Box to intersect with.

box.unionWith(box) ⇒ Box

Computes the union of this box and box. This will set the upper bound of this box to the greater of the two boxes’ upper bounds and the lower bound of this box to the lesser of the two boxes’ lower bounds.

Kind: instance method of Box
Returns: Box - Self.

Param Type Description
box Box Box to union with.

box.translate(offset) ⇒ Box

Move this box.

Kind: instance method of Box
Returns: Box - Self.

Param Type Description
offset Vector3 Offset to move box by.

box.equals(other) ⇒ Boolean

Check if equal to another box.

Kind: instance method of Box
Returns: Boolean - True if boxes are equal, false otherwise.

Param Type Description
other Box Other box to compare to.

Circle

Implement a simple 2d Circle.

Kind: global class

new Circle(center, radius)

Create the Circle.

Param Type Description
center Vector2 Circle center position.
radius Number Circle radius.

circle.clone() ⇒ Circle

Return a clone of this circle.

Kind: instance method of Circle
Returns: Circle - Cloned circle.

circle.containsVector(p) ⇒ Boolean

Check if this circle contains a Vector2.

Kind: instance method of Circle
Returns: Boolean - if point is contained within the circle.

Param Type Description
p Vector2 Point to check.

circle.equals(other) ⇒ Boolean

Check if equal to another circle.

Kind: instance method of Circle
Returns: Boolean - True if circles are equal, false otherwise.

Param Type Description
other Circle Other circle to compare to.

circle.toDict(minimized) ⇒ \*

Convert to dictionary.

Kind: instance method of Circle
Returns: \* - Dictionary with {center, radius}.

Param Type Description
minimized Boolean If true, will not include keys that their values are 0. You can use fromDict on minimized dicts.

Circle.fromDict(data) ⇒ Circle

Create circle from a dictionary.

Kind: static method of Circle
Returns: Circle - Newly created circle.

Param Type Description
data \* Dictionary with {center, radius}.

Circle.lerp(p1, p2, a) ⇒ Circle

Lerp between two circle.

Kind: static method of Circle
Returns: Circle - result circle.

Param Type Description
p1 Circle First circle.
p2 Circle Second circle.
a Number Lerp factor (0.0 - 1.0).

Color

Implement a color. All color components are expected to be in 0.0 - 1.0 range (and not 0-255).

Kind: global class

new Color(r, g, b, [a])

Create the color.

Param Type Description
r Number Color red component (value range: 0-1).
g Number Color green component (value range: 0-1).
b Number Color blue component (value range: 0-1).
[a] Number Color alpha component (value range: 0-1).

color.r ⇒ Number

Get r component.

Kind: instance property of Color
Returns: Number - Red component.

color.g ⇒ Number

Get g component.

Kind: instance property of Color
Returns: Number - Green component.

color.b ⇒ Number

Get b component.

Kind: instance property of Color
Returns: Number - Blue component.

color.a ⇒ Number

Get a component.

Kind: instance property of Color
Returns: Number - Alpha component.

color.r ⇒ Number

Set r component.

Kind: instance property of Color
Returns: Number - Red component after change.

color.g ⇒ Number

Set g component.

Kind: instance property of Color
Returns: Number - Green component after change.

color.b ⇒ Number

Set b component.

Kind: instance property of Color
Returns: Number - Blue component after change.

color.a ⇒ Number

Set a component.

Kind: instance property of Color
Returns: Number - Alpha component after change.

color.asHex ⇒ String

Convert this color to hex string (starting with ‘#’).

Kind: instance property of Color
Returns: String - Color as hex.

color.asDecimalRGBA ⇒ Number

Convert this color to decimal number.

Kind: instance property of Color
Returns: Number - Color as decimal RGBA.

color.asDecimalABGR ⇒ Number

Convert this color to decimal number.

Kind: instance property of Color
Returns: Number - Color as decimal ARGB.

color.floatArray

Convert this color to a float array.

Kind: instance property of Color

color.isBlack

Get if this color is pure black (ignoring alpha).

Kind: instance property of Color

color.isTransparentBlack

Get if this color is transparent black.

Kind: instance property of Color

color.set(r, g, b, a) ⇒ Color

Set the color components.

Kind: instance method of Color
Returns: Color - this.

Param Type Description
r Number Color red component (value range: 0-1).
g Number Color green component (value range: 0-1).
b Number Color blue component (value range: 0-1).
a Number Color alpha component (value range: 0-1).

color.setByte(r, g, b, a) ⇒ Color

Set the color components from byte values (0-255).

Kind: instance method of Color
Returns: Color - this.

Param Type Description
r Number Color red component (value range: 0-255).
g Number Color green component (value range: 0-255).
b Number Color blue component (value range: 0-255).
a Number Color alpha component (value range: 0-255).

color.copy(other) ⇒ Color

Copy all component values from another color.

Kind: instance method of Color
Returns: Color - this.

Param Type Description
other Color Color to copy values from.

color.toDict(minimized) ⇒ \*

Convert to dictionary.

Kind: instance method of Color
Returns: \* - Dictionary with {r,g,b,a}

Param Type Description
minimized Boolean If true, will not include keys that their values are 1. You can use fromDict on minimized dicts.

color.clone() ⇒ Number

Return a clone of this color.

Kind: instance method of Color
Returns: Number - Cloned color.

color.string()

Convert to string.

Kind: instance method of Color

color.equals(other)

Check if equal to another color.

Kind: instance method of Color

Param Type Description
other Color Other color to compare to.

Color.webColorNames ⇒ Array.<String>

Get array with all built-in web color names.

Kind: static property of Color
Returns: Array.<String> - Array with color names.

Color.componentToHex(c) ⇒ String

Convert a single component to hex value.

Kind: static method of Color
Returns: String - Component as hex value.

Param Type Description
c Number Value to convert to hex.

Color.fromHex(val) ⇒ Color

Create color from hex value.

Kind: static method of Color
Returns: Color - New color value.

Param Type Description
val String Number value (hex), as #rrggbbaa.

Color.fromDecimal(val, includeAlpha) ⇒ Color

Create color from decimal value.

Kind: static method of Color
Returns: Color - New color value.

Param Type Description
val Number Number value (int).
includeAlpha Number If true, will include alpha value.

Color.fromDict(data) ⇒ Color

Create color from a dictionary.

Kind: static method of Color
Returns: Color - Newly created color.

Param Type Description
data \* Dictionary with {r,g,b,a}.

Color.random(includeAlpha) ⇒ Color

Return a random color.

Kind: static method of Color
Returns: Color - Randomized color.

Param Type Description
includeAlpha Boolean If true, will also randomize alpha.

Color.fromBytesArray(bytes, [offset]) ⇒ Color

Build and return new color from bytes array.

Kind: static method of Color
Returns: Color - Newly created color.

Param Type Description
bytes Array.<Number> Bytes array to build color from.
[offset] Number Optional offset to read bytes from.

Color.lerp(p1, p2, a) ⇒ Color

Lerp between two colors.

Kind: static method of Color
Returns: Color - result color.

Param Type Description
p1 Color First color.
p2 Color Second color.
a Number Lerp factor (0.0 - 1.0).

Frustum

Implement a 3D Frustum shape.

Kind: global class

new Frustum(p0, p1, p2, p3, p4, p5)

Create the frustum.

Param Type Description
p0 Plane Frustum plane.
p1 Plane Frustum plane.
p2 Plane Frustum plane.
p3 Plane Frustum plane.
p4 Plane Frustum plane.
p5 Plane Frustum plane.

frustum.set(p0, p1, p2, p3, p4, p5) ⇒ Frustum

Set the Frustum values.

Kind: instance method of Frustum
Returns: Frustum - Self.

Param Type Description
p0 Plane Frustum plane.
p1 Plane Frustum plane.
p2 Plane Frustum plane.
p3 Plane Frustum plane.
p4 Plane Frustum plane.
p5 Plane Frustum plane.

frustum.copy(frustum) ⇒ Frustum

Copy values from another frustum.

Kind: instance method of Frustum
Returns: Frustum - Self.

Param Type Description
frustum Frustum Frustum to copy.

frustum.setFromProjectionMatrix(m) ⇒ Frustum

Set frustum from projection matrix.

Kind: instance method of Frustum
Returns: Frustum - Self.

Param Type Description
m Matrix Matrix to build frustum from.

frustum.collideSphere(sphere) ⇒ Boolean

Check if the frustum collides with a sphere.

Kind: instance method of Frustum
Returns: Boolean - True if point is in frustum, false otherwise.

Param Type Description
sphere Sphere Sphere to check.

frustum.collideBox(box) ⇒ Boolean

Check if collide with a box.

Kind: instance method of Frustum
Returns: Boolean - True if collide, false otherwise.

Param Type Description
box Box Box to check.

frustum.containsPoint(point) ⇒ Boolean

Check if the frustum contains a point.

Kind: instance method of Frustum
Returns: Boolean - True if point is in frustum, false otherwise.

Param Type Description
point Vector3 Vector to check.

frustum.clone() ⇒ Frustum

Clone this frustum.

Kind: instance method of Frustum
Returns: Frustum - Cloned frustum.

GameTime

Class to hold current game time, both elapse and delta from last frame.

Kind: global class

new GameTime()

create the gametime object with current time.

gameTime.timestamp

Current timestamp

Kind: instance property of GameTime

gameTime.deltaTime

Delta time struct. Contains: milliseconds, seconds.

Kind: instance property of GameTime

gameTime.elapsedTime

Elapsed time struct. Contains: milliseconds, seconds.

Kind: instance property of GameTime

gameTime.delta

Delta time, in seconds, since last frame.

Kind: instance property of GameTime

gameTime.elapsed

Total time, in seconds, since Shaku was initialized.

Kind: instance property of GameTime

gameTime.rawTimestamp

Raw timestamp in milliseconds. This value updates only as long as you run Shaku frames, and continue to update even if game is paused.

Kind: instance property of GameTime

GameTime.rawTimestamp() ⇒ Number

Get raw timestamp in milliseconds. This value updates only as long as you run Shaku frames, and continue to update even if game is paused.

Kind: static method of GameTime
Returns: Number - raw timestamp in milliseconds.

GameTime.reset()

Reset elapsed and delta time.

Kind: static method of GameTime

GameTime.resetDelta()

Reset current frame’s delta time.

Kind: static method of GameTime

ItemsSorter

Utility class to arrange rectangles in minimal region.

Kind: global class

ItemsSorter.arrangeRectangles(rectangles, [processRegionWidthMethod], [extraMargins]) ⇒ \*

Efficiently arrange rectangles into a minimal size area. Based on code from here: https://github.com/mapbox/potpack

Kind: static method of ItemsSorter
Returns: \* - Result object with the following keys: {width, height, rectangles, utilized}. width = required container width. height = required container width. rectangles = list of sorted rectangles. every entry has {x, y, width, height, source} where x and y are the offset in container and source is the source input object. utilized = how much of the output space was utilized.

Param Type Description
rectangles Array.<(Rectangle\|Vector2\|\*)> Array of vectors or rectangles to sort. If the object have ‘width’ and ‘height’ properties, these properties will be used to define the rectangle size. If not but the object have ‘x’ and ‘y’ properties, x and y will be taken instead. The source object will be included in the result objects.
[processRegionWidthMethod] function If provided, will run this method when trying to decide on the result region width. Method receive desired width as argument, and return a new width to override the decision. You can use this method to limit max width or round it to multiplies of 2 for textures. Note: by default, the algorithm will try to create a square region.
[extraMargins] Vector2 Optional extra empty pixels to add between textures in atlas.

Example

// 'id' will be used to identify the items after the sort.
let boxes = [{x: 100, y: 50, id: 1}, {x: 50, y: 70, id: 2}, {x: 125, y: 85, id: 3}, ... more boxes here ];
let result = RectanglesSorter.arrangeRectangles(boxes);
// show result
console.log(`Output region size is: ${result.width},${result.height}, and it utilizes ${result.utilized} of the area.`);
for (let res of result.rectangles) {
  console.log(`Rectangle ${res.source.id} is at position: ${res.x},${res.y}.`);
}

Line

Implement a simple 2d Line.

Kind: global class

new Line(from, to)

Create the Line.

Param Type Description
from Vector2 Line start position.
to Vector2 Line end position.

line.clone() ⇒ Line

Return a clone of this line.

Kind: instance method of Line
Returns: Line - Cloned line.

line.toDict(minimized) ⇒ \*

Convert to dictionary.

Kind: instance method of Line
Returns: \* - Dictionary with {from, to}.

Param Type Description
minimized Boolean If true, will not include keys that their values are 0. You can use fromDict on minimized dicts.

line.containsVector(p, threshold) ⇒ Boolean

Check if this circle contains a Vector2.

Kind: instance method of Line
Returns: Boolean - if point is contained within the circle.

Param Type Description
p Vector2 Point to check.
threshold Number Distance between point and line to consider as intersecting. Default is 0.5, meaning it will treat point and line as round integers (sort-of).

line.collideLine(other) ⇒ Boolean

Check if this line collides with another line.

Kind: instance method of Line
Returns: Boolean - True if lines collide, false otherwise.

Param Type Description
other Line Other line to test collision with.

line.distanceToVector(v) ⇒ Number

Get the shortest distance between this line segment and a vector.

Kind: instance method of Line
Returns: Number - Shortest distance between line and vector.

Param Type Description
v Vector2 Vector to get distance to.

line.equals(other) ⇒ Boolean

Check if equal to another circle.

Kind: instance method of Line
Returns: Boolean - True if circles are equal, false otherwise.

Param Type Description
other Circle Other circle to compare to.

Line.fromDict(data) ⇒ Line

Create Line from a dictionary.

Kind: static method of Line
Returns: Line - Newly created line.

Param Type Description
data \* Dictionary with {from, to}.

Line.lerp(l1, l2, a) ⇒ Line

Lerp between two lines.

Kind: static method of Line
Returns: Line - result lines.

Param Type Description
l1 Line First lines.
l2 Line Second lines.
a Number Lerp factor (0.0 - 1.0).

MathHelper

Implement some math utilities functions.

Kind: global class

MathHelper.lerp(start, end, amount) ⇒ Number

Perform linear interpolation between start and end values.

Kind: static method of MathHelper
Returns: Number - interpolated value between start and end.

Param Type Description
start Number Starting value.
end Number Ending value.
amount Number How much to interpolate from start to end.

MathHelper.dot(x1, y1, x2, y2) ⇒ Number

Calculate 2d dot product.

Kind: static method of MathHelper
Returns: Number - dot product result.

Param Type Description
x1 Number First vector x.
y1 Number First vector y.
x2 Number Second vector x.
y2 Number Second vector y.

MathHelper.roundToMultiple(numToRound, multiple) ⇒ Number

Make a number a multiply of another number by rounding it up.

Kind: static method of MathHelper
Returns: Number - Result number.

Param Type Description
numToRound Number Number to round up.
multiple Number Number to make ‘numToRound’ a multiply of.

MathHelper.toRadians(degrees) ⇒ Number

Convert degrees to radians.

Kind: static method of MathHelper
Returns: Number - Value as radians.

Param Type Description
degrees Number Degrees value to convert to radians.

MathHelper.toDegrees(radians) ⇒ Number

Convert radians to degrees.

Kind: static method of MathHelper
Returns: Number - Value as degrees.

Param Type Description
radians Number Radians value to convert to degrees.

MathHelper.radiansDistanceSigned(a1, a2) ⇒ Number

Find shortest distance between two radians, with sign (ie distance can be negative).

Kind: static method of MathHelper
Returns: Number - Shortest distance between radians.

Param Type Description
a1 Number First radian.
a2 Number Second radian.

MathHelper.radiansDistance(a1, a2) ⇒ Number

Find shortest distance between two radians.

Kind: static method of MathHelper
Returns: Number - Shortest distance between radians.

Param Type Description
a1 Number First radian.
a2 Number Second radian.

MathHelper.degreesDistanceSigned(a1, a2) ⇒ Number

Find shortest distance between two angles in degrees, with sign (ie distance can be negative).

Kind: static method of MathHelper
Returns: Number - Shortest distance between angles.

Param Type Description
a1 Number First angle.
a2 Number Second angle.

MathHelper.degreesDistance(a1, a2) ⇒ Number

Find shortest distance between two angles in degrees.

Kind: static method of MathHelper
Returns: Number - Shortest distance between angles.

Param Type Description
a1 Number First angle.
a2 Number Second angle.

MathHelper.lerpRadians(a1, a2, alpha) ⇒ Number

Perform linear interpolation between radian values. Unlike the regular lerp method, this method will take wrapping into consideration, and will always lerp via the shortest distance.

Kind: static method of MathHelper
Returns: Number - interpolated radians between start and end.

Param Type Description
a1 Number Starting value.
a2 Number Ending value.
alpha Number How much to interpolate from start to end.

MathHelper.lerpDegrees(a1, a2, alpha) ⇒ Number

Perform linear interpolation between degrees. Unlike the regular lerp method, this method will take wrapping into consideration, and will always lerp via the shortest distance.

Kind: static method of MathHelper
Returns: Number - interpolated degrees between start and end.

Param Type Description
a1 Number Starting value.
a2 Number Ending value.
alpha Number How much to interpolate from start to end.

MathHelper.round10(num) ⇒ Number

Round numbers from 10’th digit. This is useful for calculations that should return round or almost round numbers, but have a long tail of 0’s and 1 due to floating points accuracy.

Kind: static method of MathHelper
Returns: Number - Rounded number.

Param Type Description
num Number Number to round.

MathHelper.wrapDegrees(degrees) ⇒ Number

Wrap degrees value to be between 0 to 360.

Kind: static method of MathHelper
Returns: Number - degrees wrapped to be 0-360 values.

Param Type Description
degrees Number Degrees to wrap.

MathHelper.calculateNormal(v1, v2, v3) ⇒ Vector3

Calculate the normal vector of a polygon using 3 points on it.

Kind: static method of MathHelper
Returns: Vector3 - Normal vector, normalized.

Param Type Description
v1 Vector3 Vector on the polygon.
v2 Vector3 Vector on the polygon.
v3 Vector3 Vector on the polygon.

Matrix

Implements a matrix.

Kind: global class

new Matrix(values, cloneValues)

Create the matrix.

Param Description
values matrix values array.
cloneValues if true or undefined, will clone values instead of just holding a reference to them.

matrix.set()

Set the matrix values.

Kind: instance method of Matrix

matrix.clone() ⇒ Matrix

Clone the matrix.

Kind: instance method of Matrix
Returns: Matrix - Cloned matrix.

matrix.equals(other) ⇒ Boolean

Compare this matrix to another matrix.

Kind: instance method of Matrix
Returns: Boolean - If matrices are the same.

Param Type Description
other Matrix Matrix to compare to.

matrix.inverted() ⇒ Matrix

Clone and invert the matrix.

Kind: instance method of Matrix
Returns: Matrix - Clonsed inverted matrix.

matrix.invertSelf() ⇒ Matrix

Invert this matrix.

Kind: instance method of Matrix
Returns: Matrix - Self.

matrix.transform(target) ⇒ Vector2 | Vector3 | Vector3

Transform a target.

Kind: instance method of Matrix
Returns: Vector2 | Vector3 | Vector3 - Transformed result.

Param Type Description
target Vector2 | Vector3 | Vertex Transforms a target, that can be vector2, vector3, or vertex.

matrix.multiplySelfWith(other) ⇒ Matrix

Multiply this matrix with another matrix, putting results in self.

Kind: instance method of Matrix
Returns: Matrix - This.

Param Type Description
other Matrix Matrix to multiply with.

matrix.multiplyWith(other) ⇒ Matrix

Multiply this matrix with another matrix and return a new result matrix.

Kind: instance method of Matrix
Returns: Matrix - New result matrix.

Param Type Description
other Matrix Matrix to multiply with.

Matrix.createOrthographic() ⇒ Matrix

Create an orthographic projection matrix.

Kind: static method of Matrix
Returns: Matrix - a new matrix with result.

Matrix.createPerspective() ⇒ Matrix

Create a perspective projection matrix.

Kind: static method of Matrix
Returns: Matrix - a new matrix with result.

Matrix.createTranslation() ⇒ Matrix

Create a translation matrix.

Kind: static method of Matrix
Returns: Matrix - a new matrix with result.

Matrix.createScale() ⇒ Matrix

Create a scale matrix.

Kind: static method of Matrix
Returns: Matrix - a new matrix with result.

Matrix.createRotationX() ⇒ Matrix

Create a rotation matrix around X axis.

Kind: static method of Matrix
Returns: Matrix - a new matrix with result.

Matrix.createRotationY() ⇒ Matrix

Create a rotation matrix around Y axis.

Kind: static method of Matrix
Returns: Matrix - a new matrix with result.

Matrix.createRotationZ() ⇒ Matrix

Create a rotation matrix around Z axis.

Kind: static method of Matrix
Returns: Matrix - a new matrix with result.

Matrix.multiply() ⇒ Matrix

Multiply two matrices.

Kind: static method of Matrix
Returns: Matrix - a new matrix with result.

Matrix.createLookAt(eyePosition, targetPosition, [upVector]) ⇒ Matrix

Creates a look-at matrix - a matrix rotated to look at a given position.

Kind: static method of Matrix
Returns: Matrix - a new matrix with result.

Param Type Description
eyePosition Vector3 Eye position.
targetPosition Vector3 Position the matrix should look at.
[upVector] Vector3 Optional vector representing ‘up’ direction.

Matrix.multiplyMany(matrices) ⇒ Matrix

Multiply an array of matrices.

Kind: static method of Matrix
Returns: Matrix - new matrix with multiply result.

Param Type Description
matrices Array.<Matrix> Matrices to multiply.

Matrix.multiplyIntoFirst() ⇒ Matrix

Multiply two matrices and put result in first matrix.

Kind: static method of Matrix
Returns: Matrix - matrixA, after it was modified.

Matrix.multiplyManyIntoFirst(matrices) ⇒ Matrix

Multiply an array of matrices into the first matrix in the array.

Kind: static method of Matrix
Returns: Matrix - first matrix in array, after it was modified.

Param Type Description
matrices Array.<Matrix> Matrices to multiply.

Matrix.transformVertex(matrix, vertex) ⇒ Vertex

Transform a 2d vertex.

Kind: static method of Matrix
Returns: Vertex - A transformed vertex (cloned, not the original).

Param Type Description
matrix Matrix Matrix to use to transform vector.
vertex Vertex Vertex to transform.

Matrix.transformVector2(matrix, vector) ⇒ Vector2

Transform a 2d vector.

Kind: static method of Matrix
Returns: Vector2 - Transformed vector.

Param Type Description
matrix Matrix Matrix to use to transform vector.
vector Vector2 Vector to transform.

Matrix.transformVector3(matrix, vector) ⇒ Vector3

Transform a 3d vector.

Kind: static method of Matrix
Returns: Vector3 - Transformed vector.

Param Type Description
matrix Matrix Matrix to use to transform vector.
vector Vector3 Vector to transform.

IGrid

Interface for a supported grid.

Kind: global class

iGrid.isBlocked(_from, _to) ⇒ Boolean

Check if a given tile is blocked from a given neihbor.

Kind: instance method of IGrid
Returns: Boolean - Can we travel from _from to _to?

Param Type Description
_from Vector2 | Vector3 Source tile index.
_to Vector2 | Vector3 Target tile index. Must be a neighbor of _from.

iGrid.getPrice(_index) ⇒ Number

Get the price to travel on a given tile. Should return 1 for “normal” traveling price, > 1 for expensive tile, and < 1 for a cheap tile to pass on.

Kind: instance method of IGrid
Returns: Number - Price factor to walk on.

Param Type Description
_index Vector2 | Vector3 Tile index.

Node

A path node.

Kind: global class

new Node(position)

Create the node from a position.

Param Type Description
position Vector2 | Vector3 Node position.

node.fCost

Get the node fCost factor.

Kind: instance property of Node

Perlin

Generate 2d perlin noise. Based on code from noisejs by Stefan Gustavson. https://github.com/josephg/noisejs/blob/master/perlin.js

Kind: global class

new Perlin(seed)

Create the perlin noise generator.

Param Type Description
seed Number Seed for perlin noise, or undefined for random.

perlin.seed(seed)

Set the perlin noise seed.

Kind: instance method of Perlin

Param Type Description
seed Number New seed value. May be either a decimal between 0 to 1, or an unsigned short between 0 to 65536.

perlin.generateSmooth(x, y, blurDistance, contrast) ⇒ Number

Generate a perlin noise value for x,y coordinates.

Kind: instance method of Perlin
Returns: Number - Perlin noise value for given point.

Param Type Description
x Number X coordinate to generate perlin noise for.
y Number Y coordinate to generate perlin noise for.
blurDistance Number Distance to take neighbors to blur returned value with. Defaults to 0.25.
contrast Number Optional contrast factor.

perlin.generate(x, y, contrast) ⇒ Number

Generate a perlin noise value for x,y coordinates.

Kind: instance method of Perlin
Returns: Number - Perlin noise value for given point, ranged from 0 to 1.

Param Type Description
x Number X coordinate to generate perlin noise for.
y Number Y coordinate to generate perlin noise for.
contrast Number Optional contrast factor.

Plane

A plane in 3D space.

Kind: global class

new Plane(normal, constant)

Create the plane.

Param Type Default Description
normal Vector3   Plane normal vector.
constant Number 0 Plane constant.

plane.set(normal, constant) ⇒ Plane

Set the plane components.

Kind: instance method of Plane
Returns: Plane - Self.

Param Type Description
normal Vector3 Plane normal.
constant Number Plane constant.

plane.setComponents(x, y, z, w) ⇒ Plane

Set the plane components.

Kind: instance method of Plane
Returns: Plane - Self.

Param Type Description
x Number Plane normal X.
y Number Plane normal Y.
z Number Plane normal Z.
w Number Plane constant.

plane.setFromNormalAndCoplanarPoint(normal, point) ⇒ Plane

Set plane from normal and coplanar point vectors.

Kind: instance method of Plane
Returns: Plane - Self.

Param Type Description
normal Vector3 Plane normal.
point Vector3 Coplanar point.

plane.copy(plane) ⇒ Plane

Copy values from another plane.

Kind: instance method of Plane
Returns: Plane - Self.

Param Type Description
plane Plane Plane to copy.

plane.normalizeSelf() ⇒ Plane

Normalize the plane.

Kind: instance method of Plane
Returns: Plane - self.

plane.normalized() ⇒ Plane

Normalize a clone of this plane.

Kind: instance method of Plane
Returns: Plane - Normalized clone.

plane.negateSelf() ⇒ Plane

Negate this plane.

Kind: instance method of Plane
Returns: Plane - Self.

plane.distanceToPoint(point) ⇒ Number

Calculate distance to point.

Kind: instance method of Plane
Returns: Number - Distance to point.

Param Type Description
point Vector3 Point to calculate distance to.

plane.distanceToSphere(sphere) ⇒ Number

Calculate distance to sphere.

Kind: instance method of Plane
Returns: Number - Distance to sphere.

Param Type Description
sphere Sphere Sphere to calculate distance to.

plane.collideLine(line) ⇒ Boolean

Check if this plane collide with a line.

Kind: instance method of Plane
Returns: Boolean - True if collide, false otherwise.

Param Type Description
line Line Line to check.

plane.collideSphere(sphere) ⇒ Boolean

Check if this plane collide with a sphere.

Kind: instance method of Plane
Returns: Boolean - True if collide, false otherwise.

Param Type Description
sphere Sphere Sphere to check.

plane.coplanarPoint() ⇒ Vector3

Coplanar a point.

Kind: instance method of Plane
Returns: Vector3 - Coplanar point as a new vector.

plane.translateSelf(offset) ⇒ Plane

Translate this plane.

Kind: instance method of Plane
Returns: Plane - Self.

Param Type Description
offset Vector3 Offset to translate to.

plane.equals(plane) ⇒ Boolean

Check if this plane equals another plane.

Kind: instance method of Plane
Returns: Boolean - True if equal, false otherwise.

Param Type Description
plane Plane Other plane to compare to.

plane.clone() ⇒ Plane

Clone this plane.

Kind: instance method of Plane
Returns: Plane - Cloned plane.

Ray

A 3D ray.

Kind: global class

new Ray(origin, direction)

Create the Ray.

Param Type Description
origin Vector3 Ray origin point.
direction Vector3 Ray 3d direction.

ray.set(origin, direction) ⇒ Plane

Set the ray components.

Kind: instance method of Ray
Returns: Plane - Self.

Param Type Description
origin Vector3 Ray origin point.
direction Vector3 Ray 3d direction.

ray.copy(ray) ⇒ Ray

Copy values from another ray.

Kind: instance method of Ray
Returns: Ray - Self.

Param Type Description
ray Ray Ray to copy.

ray.equals(ray) ⇒ Boolean

Check if this ray equals another ray.

Kind: instance method of Ray
Returns: Boolean - True if equal, false otherwise.

Param Type Description
ray Ray Other ray to compare to.

ray.at(distance) ⇒ Vector3

Get the 3d point on the ray by distance from origin.

Kind: instance method of Ray
Returns: Vector3 - Point on ray from origin.

Param Type Description
distance Number Distance from origin to travel.

ray.distanceToPoint(point) ⇒ Number

Calculate distance to a 3d point.

Kind: instance method of Ray
Returns: Number - Distance to point.

Param Type Description
point Vector3 Point to calculate distance to.

ray.distanceToPointSquared(point) ⇒ Number

Calculate squared distance to a 3d point.

Kind: instance method of Ray
Returns: Number - Squared distance to point.

Param Type Description
point Vector3 Point to calculate distance to.

ray.collideSphere(sphere) ⇒ Boolean

Check if this ray collides with a sphere.

Kind: instance method of Ray
Returns: Boolean - True if collide with sphere, false otherwise.

Param Type Description
sphere Sphere Sphere to test collision with.

ray.collideBox(box) ⇒ Boolean

Check if this ray collides with a box.

Kind: instance method of Ray
Returns: Boolean - True if collide with box, false otherwise.

Param Type Description
box Box Box to test collision with.

ray.findColliionPointWithBox(box) ⇒ Vector3 | null

Return the collision point between the ray and a box, or null if they don’t collide.

Kind: instance method of Ray
Returns: Vector3 | null - Collision point or null.

Param Type Description
box Box Box to get collision with.

ray.clone() ⇒ Ray

Clone this ray.

Kind: instance method of Ray
Returns: Ray - Cloned ray.

Rectangle

Implement a simple 2d Rectangle.

Kind: global class

new Rectangle(x, y, width, height)

Create the Rect.

Param Type Description
x Number Rect position X (top left corner).
y Number Rect position Y (top left corner).
width Number Rect width.
height Number Rect height.

rectangle.left ⇒ Number

Get left value.

Kind: instance property of Rectangle
Returns: Number - rectangle left.

rectangle.right ⇒ Number

Get right value.

Kind: instance property of Rectangle
Returns: Number - rectangle right.

rectangle.top ⇒ Number

Get top value.

Kind: instance property of Rectangle
Returns: Number - rectangle top.

rectangle.bottom ⇒ Number

Get bottom value.

Kind: instance property of Rectangle
Returns: Number - rectangle bottom.

rectangle.set(x, y, width, height) ⇒ Rectangle

Set rectangle values.

Kind: instance method of Rectangle
Returns: Rectangle - this.

Param Type Description
x Number Rectangle x position.
y Number Rectangle y position.
width Number Rectangle width.
height Number Rectangle height.

rectangle.copy(other) ⇒ Rectangle

Copy another rectangle.

Kind: instance method of Rectangle
Returns: Rectangle - this.

Param Type Description
other other Rectangle to copy.

rectangle.getPosition() ⇒ Vector2

Get position as Vector2.

Kind: instance method of Rectangle
Returns: Vector2 - Position vector.

rectangle.getSize() ⇒ Vector2

Get size as Vector2.

Kind: instance method of Rectangle
Returns: Vector2 - Size vector.

rectangle.getCenter() ⇒ Vector2

Get center position.

Kind: instance method of Rectangle
Returns: Vector2 - Position vector.

rectangle.clone() ⇒ Rectangle

Return a clone of this rectangle.

Kind: instance method of Rectangle
Returns: Rectangle - Cloned rectangle.

rectangle.getTopLeft() ⇒ Vector2

Get top-left corner.

Kind: instance method of Rectangle
Returns: Vector2 - Corner position vector.

rectangle.getTopRight() ⇒ Vector2

Get top-right corner.

Kind: instance method of Rectangle
Returns: Vector2 - Corner position vector.

rectangle.getBottomLeft() ⇒ Vector2

Get bottom-left corner.

Kind: instance method of Rectangle
Returns: Vector2 - Corner position vector.

rectangle.getBottomRight() ⇒ Vector2

Get bottom-right corner.

Kind: instance method of Rectangle
Returns: Vector2 - Corner position vector.

rectangle.string()

Convert to string.

Kind: instance method of Rectangle

rectangle.containsVector(p) ⇒ Boolean

Check if this rectangle contains a Vector2.

Kind: instance method of Rectangle
Returns: Boolean - if point is contained within the rectangle.

Param Type Description
p Vector2 Point to check.

rectangle.collideRect(other) ⇒ Boolean

Check if this rectangle collides with another rectangle.

Kind: instance method of Rectangle
Returns: Boolean - if rectangles collide.

Param Type Description
other Rectangle Rectangle to check collision with.

rectangle.collideLine(line) ⇒ Boolean

Check if this rectangle collides with a line.

Kind: instance method of Rectangle
Returns: Boolean - if rectangle collides with line.

Param Type Description
line Line Line to check collision with.

rectangle.collideCircle(circle) ⇒ Boolean

Checks if this rectangle collides with a circle.

Kind: instance method of Rectangle
Returns: Boolean - if rectangle collides with circle.

Param Type Description
circle Circle Circle to check collision with.

rectangle.getBoundingCircle() ⇒ Circle

Get the smallest circle containing this rectangle.

Kind: instance method of Rectangle
Returns: Circle - Bounding circle.

rectangle.resize(amount) ⇒ Rectangle

Return a resized rectangle with the same center point.

Kind: instance method of Rectangle
Returns: Rectangle - resized rectangle.

Param Type Description
amount Number | Vector2 Amount to resize.

rectangle.equals(other)

Check if equal to another rectangle.

Kind: instance method of Rectangle

Param Type Description
other Rectangle Other rectangle to compare to.

rectangle.toDict(minimized) ⇒ \*

Convert to dictionary.

Kind: instance method of Rectangle
Returns: \* - Dictionary with {x,y,width,height}

Param Type Description
minimized Boolean If true, will not include keys that their values are 0. You can use fromDict on minimized dicts.

Rectangle.fromPoints(points) ⇒ Rectangle

Build and return a rectangle from points.

Kind: static method of Rectangle
Returns: Rectangle - new rectangle from points.

Param Type Description
points Array.<Vector2> Points to build rectangle from.

Rectangle.lerp(p1, p2, a) ⇒ Rectangle

Lerp between two rectangles.

Kind: static method of Rectangle
Returns: Rectangle - result rectangle.

Param Type Description
p1 Rectangle First rectangles.
p2 Rectangle Second rectangles.
a Number Lerp factor (0.0 - 1.0).

Rectangle.fromDict(data) ⇒ Rectangle

Create rectangle from a dictionary.

Kind: static method of Rectangle
Returns: Rectangle - Newly created rectangle.

Param Type Description
data \* Dictionary with {x,y,width,height}.

SeededRandom

Class to generate random numbers with seed.

Kind: global class

new SeededRandom(seed)

Create the seeded random object.

Param Type Description
seed Number Seed to start from. If not provided, will use 0.

seededRandom.random(min, max) ⇒ Number

Get next random value.

Kind: instance method of SeededRandom
Returns: Number - A randomly generated value.

Param Type Description
min Number Optional min value. If max is not provided, this will be used as max.
max Number Optional max value.

seededRandom.pick(options) ⇒ \*

Pick a random value from array.

Kind: instance method of SeededRandom
Returns: \* - Random value from options array.

Param Type Description
options Array Options to pick random value from.

Sphere

A 3D sphere.

Kind: global class

new Sphere(center, radius)

Create the Sphere.

Param Type Description
center Vector3 Sphere center position.
radius Number Sphere radius.

sphere.clone() ⇒ Sphere

Return a clone of this sphere.

Kind: instance method of Sphere
Returns: Sphere - Cloned sphere.

sphere.containsVector(p) ⇒ Boolean

Check if this sphere contains a Vector3.

Kind: instance method of Sphere
Returns: Boolean - if point is contained within the sphere.

Param Type Description
p Vector3 Point to check.

sphere.equals(other) ⇒ Boolean

Check if equal to another sphere.

Kind: instance method of Sphere
Returns: Boolean - True if spheres are equal, false otherwise.

Param Type Description
other Sphere Other sphere to compare to.

sphere.toDict(minimized) ⇒ \*

Convert to dictionary.

Kind: instance method of Sphere
Returns: \* - Dictionary with {center, radius}.

Param Type Description
minimized Boolean If true, will not include keys that their values are 0. You can use fromDict on minimized dicts.

sphere.collideBox(box) ⇒ Boolean

Check if collide with a box.

Kind: instance method of Sphere
Returns: Boolean - True if collide, false otherwise.

Param Type Description
box Box Box to check.

sphere.collidePlane(plane) ⇒ Boolean

Check if collide with a plane.

Kind: instance method of Sphere
Returns: Boolean - True if collide, false otherwise.

Param Type Description
plane Plane Plane to test.

Sphere.fromDict(data) ⇒ Sphere

Create sphere from a dictionary.

Kind: static method of Sphere
Returns: Sphere - Newly created sphere.

Param Type Description
data \* Dictionary with {center, radius}.

Sphere.lerp(p1, p2, a) ⇒ Sphere

Lerp between two sphere.

Kind: static method of Sphere
Returns: Sphere - result sphere.

Param Type Description
p1 Sphere First sphere.
p2 Sphere Second sphere.
a Number Lerp factor (0.0 - 1.0).

Storage

A thin wrapper layer around storage utility.

Kind: global class

new Storage(adapters, prefix, valuesAsBase64, keysAsBase64)

Create the storage.

Param Type Description
adapters Array.<StorageAdapter> List of storage adapters to pick from. Will use the first option returning ‘isValid()’ = true.
prefix String Optional prefix to add to all keys under this storage instance.
valuesAsBase64 Boolean If true, will encode and decode data as base64.
keysAsBase64 Boolean If true, will encode and decode keys as base64.

storage.persistent ⇒ Boolean

Return if this storage adapter is persistent storage or not.

Kind: instance property of Storage
Returns: Boolean - True if this storage type is persistent.

storage.isValid ⇒ Boolean

Check if this storage instance has a valid adapter.

Kind: instance property of Storage
Returns: Boolean - True if found a valid adapter to use, false otherwise.

storage.exists(key) ⇒ Boolean

Check if a key exists.

Kind: instance method of Storage
Returns: Boolean - True if key exists in storage.

Param Type Description
key String Key to check.

storage.setItem(key, value)

Set value.

Kind: instance method of Storage

Param Type Description
key String Key to set.
value String Value to set.

storage.getItem(key) ⇒ String

Get value.

Kind: instance method of Storage
Returns: String - Value or null if not set.

Param Type Description
key String Key to get.

storage.getJson(key) ⇒ \*

Get value and JSON parse it.

Kind: instance method of Storage
Returns: \* - Value as a dictionary object or null if not set.

Param Type Description
key String Key to get.

storage.setJson(key, value)

Set value as JSON.

Kind: instance method of Storage

Param Type Description
key String Key to set.
value \* Value to set as a dictionary.

storage.deleteItem(key)

Delete value.

Kind: instance method of Storage

Param Type Description
key String Key to delete.

storage.clear()

Clear all values from this storage instance, based on prefix + adapter type.

Kind: instance method of Storage

StorageAdapter

Storage adapter class that implement access to a storage device. Used by the Storage utilitiy.

Kind: global class

storageAdapter.persistent ⇒ Boolean

Return if this storage adapter is persistent storage or not.

Kind: instance property of StorageAdapter
Returns: Boolean - True if this storage type is persistent.

storageAdapter.isValid() ⇒ Boolean

Check if this adapter is OK to be used. For example, an adapter for localStorage will make sure it exists and not null.

Kind: instance method of StorageAdapter
Returns: Boolean - True if storage adapter is valid to be used.

storageAdapter.exists(key) ⇒ Boolean

Check if a key exists.

Kind: instance method of StorageAdapter
Returns: Boolean - True if key exists in storage.

Param Type Description
key String Key to check.

storageAdapter.setItem(key, value)

Set value.

Kind: instance method of StorageAdapter

Param Type Description
key String Key to set.
value String Value to set.

storageAdapter.getItem(key) ⇒ String

Get value.

Kind: instance method of StorageAdapter
Returns: String - Value or null if not set.

Param Type Description
key String Key to get.

storageAdapter.deleteItem(key)

Delete value.

Kind: instance method of StorageAdapter

Param Type Description
key String Key to delete.

storageAdapter.clear(prefix)

Clear all values from this storage device.

Kind: instance method of StorageAdapter

Param Type Description
prefix String Storage keys prefix.

StorageAdapterMemory

Implement simple memory storage adapter.

Kind: global class

new StorageAdapterMemory()

Create the memory storage adapter.

storageAdapterMemory.persistent

Kind: instance property of StorageAdapterMemory

storageAdapterMemory.isValid()

Kind: instance method of StorageAdapterMemory

storageAdapterMemory.exists()

Kind: instance method of StorageAdapterMemory

storageAdapterMemory.setItem()

Kind: instance method of StorageAdapterMemory

storageAdapterMemory.getItem()

Kind: instance method of StorageAdapterMemory

storageAdapterMemory.deleteItem()

Kind: instance method of StorageAdapterMemory

storageAdapterMemory.clear()

Kind: instance method of StorageAdapterMemory

StorageAdapterLocalStorage

Implement simple localstorage storage adapter.

Kind: global class

storageAdapterLocalStorage.persistent

Kind: instance property of StorageAdapterLocalStorage

storageAdapterLocalStorage.isValid()

Kind: instance method of StorageAdapterLocalStorage

storageAdapterLocalStorage.exists()

Kind: instance method of StorageAdapterLocalStorage

storageAdapterLocalStorage.setItem()

Kind: instance method of StorageAdapterLocalStorage

storageAdapterLocalStorage.getItem()

Kind: instance method of StorageAdapterLocalStorage

storageAdapterLocalStorage.deleteItem()

Kind: instance method of StorageAdapterLocalStorage

storageAdapterLocalStorage.clear()

Kind: instance method of StorageAdapterLocalStorage

StorageAdapterSessionStorage

Implement simple sessionStorage storage adapter.

Kind: global class

storageAdapterSessionStorage.persistent

Kind: instance property of StorageAdapterSessionStorage

storageAdapterSessionStorage.isValid()

Kind: instance method of StorageAdapterSessionStorage

storageAdapterSessionStorage.exists()

Kind: instance method of StorageAdapterSessionStorage

storageAdapterSessionStorage.setItem()

Kind: instance method of StorageAdapterSessionStorage

storageAdapterSessionStorage.getItem()

Kind: instance method of StorageAdapterSessionStorage

storageAdapterSessionStorage.deleteItem()

Kind: instance method of StorageAdapterSessionStorage

storageAdapterSessionStorage.clear()

Kind: instance method of StorageAdapterSessionStorage

Transformation

Transformations helper class to store 2d position, rotation and scale. Can also perform transformations inheritance, where we combine local with parent transformations.

Kind: global class

new Transformation(position, rotation, scale)

Create the transformations.

Param Type Description
position Vector2 Optional position value.
rotation Number Optional rotation value.
scale Vector2 Optional sscale value.

Example

// create local and world transformations
const transform = new Shaku.utils.Transformation();
const worldTransform = new Shaku.utils.Transformation();
// set offset to world transofm and rotation to local transform
worldTransform.setPosition({x: 100, y:50});
transform.setRotation(5);
// combine transformations and convert to a matrix
const combined = Shaku.utils.Transformation.combine(transform, worldTransform);
const matrix = combined.asMatrix();

transformation.onChange : function

Method to call when this transformation change. Function params: transformation instance (this), properties changed (boolean), transform modes changed (boolean).

Kind: instance property of Transformation

transformation.getPosition() ⇒ Vector2

Get position.

Kind: instance method of Transformation
Returns: Vector2 - Position.

transformation.getPositionMode() ⇒ TransformModes

Get position transformations mode.

Kind: instance method of Transformation
Returns: TransformModes - Position transformation mode.

transformation.setPosition(value) ⇒ Transformation

Set position.

Kind: instance method of Transformation
Returns: Transformation - this.

Param Type Description
value Vector2 New position.

transformation.setPositionX(value) ⇒ Transformation

Set position X value.

Kind: instance method of Transformation
Returns: Transformation - this.

Param Type Description
value Number New position.x value.

transformation.setPositionY(value) ⇒ Transformation

Set position Y value.

Kind: instance method of Transformation
Returns: Transformation - this.

Param Type Description
value Number New position.y value.

transformation.move(value) ⇒ Transformation

Move position by a given vector.

Kind: instance method of Transformation
Returns: Transformation - this.

Param Type Description
value Vector2 Vector to move position by.

transformation.setPositionMode(value) ⇒ Transformation

Set position transformations mode.

Kind: instance method of Transformation
Returns: Transformation - this.

Param Type Description
value TransformModes Position transformation mode.

transformation.getScale() ⇒ Vector2

Get scale.

Kind: instance method of Transformation
Returns: Vector2 - Scale.

transformation.getScaleMode() ⇒ TransformModes

Get scale transformations mode.

Kind: instance method of Transformation
Returns: TransformModes - Scale transformation mode.

transformation.setScale(value) ⇒ Transformation

Set scale.

Kind: instance method of Transformation
Returns: Transformation - this.

Param Type Description
value Vector2 New scale.

transformation.setScaleX(value) ⇒ Transformation

Set scale X value.

Kind: instance method of Transformation
Returns: Transformation - this.

Param Type Description
value Number New scale.x value.

transformation.setScaleY(value) ⇒ Transformation

Set scale Y value.

Kind: instance method of Transformation
Returns: Transformation - this.

Param Type Description
value Number New scale.y value.

transformation.scale(value) ⇒ Transformation

Scale by a given vector.

Kind: instance method of Transformation
Returns: Transformation - this.

Param Type Description
value Vector2 Vector to scale by.

transformation.setScaleMode(value) ⇒ Transformation

Set scale transformations mode.

Kind: instance method of Transformation
Returns: Transformation - this.

Param Type Description
value TransformModes Scale transformation mode.

transformation.getRotation() ⇒ Number

Get rotation.

Kind: instance method of Transformation
Returns: Number - rotation.

transformation.getRotationDegrees() ⇒ Number

Get rotation as degrees.

Kind: instance method of Transformation
Returns: Number - rotation.

transformation.getRotationDegreesWrapped() ⇒ Number

Get rotation as degrees, wrapped between 0 to 360.

Kind: instance method of Transformation
Returns: Number - rotation.

transformation.getRotationMode() ⇒ TransformModes

Get rotation transformations mode.

Kind: instance method of Transformation
Returns: TransformModes - Rotation transformations mode.

transformation.setRotation(value, wrap) ⇒ Transformation

Set rotation.

Kind: instance method of Transformation
Returns: Transformation - this.

Param Type Description
value Number New rotation.
wrap Boolean If true, will wrap value if out of possible range.

transformation.rotate(value, wrap) ⇒ Transformation

Rotate transformation by given radians.

Kind: instance method of Transformation
Returns: Transformation - this.

Param Type Description
value Number Rotate value in radians.
wrap Boolean If true, will wrap value if out of possible range.

transformation.setRotationDegrees(value, wrap) ⇒ Transformation

Set rotation as degrees.

Kind: instance method of Transformation
Returns: Transformation - this.

Param Type Description
value Number New rotation.
wrap Boolean If true, will wrap value if out of possible range.

transformation.rotateDegrees(value) ⇒ Transformation

Rotate transformation by given degrees.

Kind: instance method of Transformation
Returns: Transformation - this.

Param Type Description
value Number Rotate value in degrees.

transformation.setRotationMode(value) ⇒ Transformation

Set rotation transformations mode.

Kind: instance method of Transformation
Returns: Transformation - this.

Param Type Description
value TransformModes Rotation transformation mode.

transformation.equals(other) ⇒ Boolean

Check if this transformation equals another.

Kind: instance method of Transformation
Returns: Boolean - True if equal, false otherwise.

Param Type Description
other Transformation Other transform to compare to.

transformation.clone() ⇒ Transformation

Return a clone of this transformations.

Kind: instance method of Transformation
Returns: Transformation - Cloned transformations.

transformation.serialize()

Serialize this transformation into a dictionary.

Kind: instance method of Transformation

transformation.deserialize(data)

Deserialize this transformation from a dictionary.

Kind: instance method of Transformation

Param Type Description
data \* Data to set.

transformation.asMatrix() ⇒ Matrix

Create and return a transformation matrix.

Kind: instance method of Transformation
Returns: Matrix - New transformation matrix.

Transformation.combine(child, parent) ⇒ Transformation

Combine child transformations with parent transformations.

Kind: static method of Transformation
Returns: Transformation - Combined transformations.

Param Type Description
child Transformation Child transformations.
parent Transformation Parent transformations.

Vector2

A simple Vector object for 2d positions.

Kind: global class

new Vector2(x, y)

Create the Vector object.

Param Type Default Description
x number 0 Vector X.
y number 0 Vector Y.

vector2.clone() ⇒ Vector2

Clone the vector.

Kind: instance method of Vector2
Returns: Vector2 - cloned vector.

vector2.set(x, y) ⇒ Vector2

Set vector value.

Kind: instance method of Vector2
Returns: Vector2 - this.

Param Type Description
x Number X component.
y Number Y component.

vector2.copy() ⇒ Vector2

Copy values from other vector into self.

Kind: instance method of Vector2
Returns: Vector2 - this.

vector2.add(Other) ⇒ Vector2

Return a new vector of this + other.

Kind: instance method of Vector2
Returns: Vector2 - result vector.

Param Type Description
Other Number | Vector2 Vector3 or number to add to all components.

vector2.sub(Other) ⇒ Vector2

Return a new vector of this - other.

Kind: instance method of Vector2
Returns: Vector2 - result vector.

Param Type Description
Other Number | Vector2 Vector3 or number to sub from all components.

vector2.div(Other) ⇒ Vector2

Return a new vector of this / other.

Kind: instance method of Vector2
Returns: Vector2 - result vector.

Param Type Description
Other Number | Vector2 Vector3 or number to divide by all components.

vector2.mul(Other) ⇒ Vector2

Return a new vector of this * other.

Kind: instance method of Vector2
Returns: Vector2 - result vector.

Param Type Description
Other Number | Vector2 Vector2 or number to multiply with all components.

vector2.round() ⇒ Vector2

Return a round copy of this vector.

Kind: instance method of Vector2
Returns: Vector2 - result vector.

vector2.floor() ⇒ Vector2

Return a floored copy of this vector.

Kind: instance method of Vector2
Returns: Vector2 - result vector.

vector2.ceil() ⇒ Vector2

Return a ceiled copy of this vector.

Kind: instance method of Vector2
Returns: Vector2 - result vector.

vector2.minSelf(v) ⇒ Vector2

Set self values to be min values between self and a given vector.

Kind: instance method of Vector2
Returns: Vector2 - Self.

Param Type Description
v Vector2 Vector to min with.

vector2.maxSelf(v) ⇒ Vector2

Set self values to be max values between self and a given vector.

Kind: instance method of Vector2
Returns: Vector2 - Self.

Param Type Description
v Vector2 Vector to max with.

vector2.min(v) ⇒ Vector2

Create a clone vector that is the min result between self and a given vector.

Kind: instance method of Vector2
Returns: Vector2 - Result vector.

Param Type Description
v Vector2 Vector to min with.

vector2.max(v) ⇒ Vector2

Create a clone vector that is the max result between self and a given vector.

Kind: instance method of Vector2
Returns: Vector2 - Result vector.

Param Type Description
v Vector2 Vector to max with.

vector2.normalized() ⇒ Vector2

Return a normalized copy of this vector.

Kind: instance method of Vector2
Returns: Vector2 - result vector.

vector2.rotatedByRadians(radians) ⇒ Vector2

Get a copy of this vector rotated by radians.

Kind: instance method of Vector2
Returns: Vector2 - New vector with the length of this vector and direction rotated by given radians.

Param Type Description
radians Number Radians to rotate by.

vector2.rotatedByDegrees(degrees) ⇒ Vector2

Get a copy of this vector rotated by degrees.

Kind: instance method of Vector2
Returns: Vector2 - New vector with the length of this vector and direction rotated by given degrees.

Param Type Description
degrees Number Degrees to rotate by.

vector2.addSelf(Other) ⇒ Vector2

Add other vector values to self.

Kind: instance method of Vector2
Returns: Vector2 - this.

Param Type Description
Other Number | Vector2 Vector or number to add.

vector2.subSelf(Other) ⇒ Vector2

Sub other vector values from self.

Kind: instance method of Vector2
Returns: Vector2 - this.

Param Type Description
Other Number | Vector2 Vector or number to substract.

vector2.divSelf(Other) ⇒ Vector2

Divide this vector by other vector values.

Kind: instance method of Vector2
Returns: Vector2 - this.

Param Type Description
Other Number | Vector2 Vector or number to divide by.

vector2.mulSelf(Other) ⇒ Vector2

Multiply this vector by other vector values.

Kind: instance method of Vector2
Returns: Vector2 - this.

Param Type Description
Other Number | Vector2 Vector or number to multiply by.

vector2.roundSelf() ⇒ Vector2

Round self.

Kind: instance method of Vector2
Returns: Vector2 - this.

vector2.floorSelf() ⇒ Vector2

Floor self.

Kind: instance method of Vector2
Returns: Vector2 - this.

vector2.ceilSelf() ⇒ Vector2

Ceil self.

Kind: instance method of Vector2
Returns: Vector2 - this.

vector2.normalizeSelf() ⇒ Vector2

Return a normalized copy of this vector.

Kind: instance method of Vector2
Returns: Vector2 - this.

vector2.equals(other) ⇒ Boolean

Return if vector equals another vector.

Kind: instance method of Vector2
Returns: Boolean - if vectors are equal.

Param Type Description
other Vector2 Other vector to compare to.

vector2.approximate(other, threshold) ⇒ Boolean

Return if vector approximately equals another vector.

Kind: instance method of Vector2
Returns: Boolean - if vectors are equal.

Param Type Description
other Vector2 Other vector to compare to.
threshold Number Distance threshold to consider as equal. Defaults to 1.

vector2.length() ⇒ Number

Return vector length (aka magnitude).

Kind: instance method of Vector2
Returns: Number - Vector length.

vector2.scaled() ⇒ Vector2

Return a copy of this vector multiplied by a factor.

Kind: instance method of Vector2
Returns: Vector2 - result vector.

vector2.degreesTo(other) ⇒ Number

Get degrees between this vector and another vector.

Kind: instance method of Vector2
Returns: Number - Angle between vectors in degrees.

Param Type Description
other Vector2 Other vector.

vector2.radiansTo(other) ⇒ Number

Get radians between this vector and another vector.

Kind: instance method of Vector2
Returns: Number - Angle between vectors in radians.

Param Type Description
other Vector2 Other vector.

vector2.wrappedDegreesTo(other) ⇒ Number

Get degrees between this vector and another vector. Return values between 0 to 360.

Kind: instance method of Vector2
Returns: Number - Angle between vectors in degrees.

Param Type Description
other Vector2 Other vector.

vector2.wrappedRadiansTo(other) ⇒ Number

Get radians between this vector and another vector. Return values between 0 to PI2.

Kind: instance method of Vector2
Returns: Number - Angle between vectors in radians.

Param Type Description
other Vector2 Other vector.

vector2.distanceTo(other) ⇒ Number

Calculate distance between this vector and another vectors.

Kind: instance method of Vector2
Returns: Number - Distance between vectors.

Param Type Description
other Vector2 Other vector.

vector2.distanceToSquared(other) ⇒ Number

Calculate squared distance between this vector and another vector.

Kind: instance method of Vector2
Returns: Number - Distance between vectors.

Param Type Description
other Vector2 Other vector.

vector2.clamp(min, max) ⇒ Vector2

Return a clone and clamp its values to be between min and max.

Kind: instance method of Vector2
Returns: Vector2 - Clamped vector.

Param Type Description
min Vector2 Min vector.
max Vector2 Max vector.

vector2.clampSelf(min, max) ⇒ Vector2

Clamp this vector values to be between min and max.

Kind: instance method of Vector2
Returns: Vector2 - Self.

Param Type Description
min Vector2 Min vector.
max Vector2 Max vector.

vector2.dot(other) ⇒ Number

Calculate the dot product with another vector.

Kind: instance method of Vector2
Returns: Number - Dot product value.

Param Type Description
other Vector2 Vector to calculate dot with.

vector2.getDegrees() ⇒ Number

Get vector’s angle in degrees.

Kind: instance method of Vector2
Returns: Number - Vector angle in degrees.

vector2.getRadians() ⇒ Number

Get vector’s angle in radians.

Kind: instance method of Vector2
Returns: Number - Vector angle in degrees.

vector2.string()

Convert to string.

Kind: instance method of Vector2

vector2.toArray() ⇒ Array.<Number>

Convert to array of numbers.

Kind: instance method of Vector2
Returns: Array.<Number> - Vector components as array.

vector2.toDict(minimized) ⇒ \*

Convert to dictionary.

Kind: instance method of Vector2
Returns: \* - Dictionary with {x,y}

Param Type Description
minimized Boolean If true, will not include keys that their values are 0. You can use fromDict on minimized dicts.

Vector2.zero() ⇒ Vector2

Get vector (0,0).

Kind: static method of Vector2
Returns: Vector2 - result vector.

Vector2.one() ⇒ Vector2

Get vector with 1,1 values.

Kind: static method of Vector2
Returns: Vector2 - result vector.

Vector2.half() ⇒ Vector2

Get vector with 0.5,0.5 values.

Kind: static method of Vector2
Returns: Vector2 - result vector.

Vector2.left() ⇒ Vector2

Get vector with -1,0 values.

Kind: static method of Vector2
Returns: Vector2 - result vector.

Vector2.right() ⇒ Vector2

Get vector with 1,0 values.

Kind: static method of Vector2
Returns: Vector2 - result vector.

Vector2.up() ⇒ Vector2

Get vector with 0,-1 values.

Kind: static method of Vector2
Returns: Vector2 - result vector.

Vector2.down() ⇒ Vector2

Get vector with 0,1 values.

Kind: static method of Vector2
Returns: Vector2 - result vector.

Vector2.random() ⇒ Vector2

Get a random vector with length of 1.

Kind: static method of Vector2
Returns: Vector2 - result vector.

Vector2.fromDegrees(degrees) ⇒ Vector2

Get vector from degrees.

Kind: static method of Vector2
Returns: Vector2 - result vector.

Param Type Description
degrees Number Angle to create vector from (0 = vector pointing right).

Vector2.fromRadians(radians) ⇒ Vector2

Get vector from radians.

Kind: static method of Vector2
Returns: Vector2 - result vector.

Param Type Description
radians Number Angle to create vector from (0 = vector pointing right).

Vector2.lerp(p1, p2, a) ⇒ Vector2

Lerp between two vectors.

Kind: static method of Vector2
Returns: Vector2 - result vector.

Param Type Description
p1 Vector2 First vector.
p2 Vector2 Second vector.
a Number Lerp factor (0.0 - 1.0).

Vector2.degreesBetween(p1, p2) ⇒ Number

Get degrees between two vectors. Return values between -180 to 180.

Kind: static method of Vector2
Returns: Number - Angle between vectors in degrees.

Param Type Description
p1 Vector2 First vector.
p2 Vector2 Second vector.

Vector2.radiansBetween(p1, p2) ⇒ Number

Get radians between two vectors. Return values between -PI to PI.

Kind: static method of Vector2
Returns: Number - Angle between vectors in radians.

Param Type Description
p1 Vector2 First vector.
p2 Vector2 Second vector.

Vector2.wrappedDegreesBetween(p1, p2) ⇒ Number

Get degrees between two vectors. Return values between 0 to 360.

Kind: static method of Vector2
Returns: Number - Angle between vectors in degrees.

Param Type Description
p1 Vector2 First vector.
p2 Vector2 Second vector.

Vector2.wrappedRadiansBetween(p1, p2) ⇒ Number

Get radians between two vectors. Return values between 0 to PI2.

Kind: static method of Vector2
Returns: Number - Angle between vectors in radians.

Param Type Description
p1 Vector2 First vector.
p2 Vector2 Second vector.

Vector2.distance(p1, p2) ⇒ Number

Calculate distance between two vectors.

Kind: static method of Vector2
Returns: Number - Distance between vectors.

Param Type Description
p1 Vector2 First vector.
p2 Vector2 Second vector.

Vector2.cross(p1, p2) ⇒ Number

Return cross product between two vectors.

Kind: static method of Vector2
Returns: Number - Cross between vectors.

Param Type Description
p1 Vector2 First vector.
p2 Vector2 Second vector.

Vector2.dot(p1, p2) ⇒ Number

Return dot product between two vectors.

Kind: static method of Vector2
Returns: Number - Dot between vectors.

Param Type Description
p1 Vector2 First vector.
p2 Vector2 Second vector.

Vector2.parse(str) ⇒ Vector2

Parse and return a vector object from string in the form of “x,y”.

Kind: static method of Vector2
Returns: Vector2 - Parsed vector.

Param Type Description
str String String to parse.

Vector2.fromArray(arr) ⇒ Vector2

Create vector from array of numbers.

Kind: static method of Vector2
Returns: Vector2 - Vector instance.

Param Type Description
arr Array.<Number> Array of numbers to create vector from.

Vector2.fromDict(data) ⇒ Vector2

Create vector from a dictionary.

Kind: static method of Vector2
Returns: Vector2 - Newly created vector.

Param Type Description
data \* Dictionary with {x,y}.

Vector3

A Vector object for 3d positions.

Kind: global class

new Vector3(x, y, z)

Create the Vector object.

Param Type Default Description
x number 0 Vector X.
y number 0 Vector Y.
z number 0 Vector Z.

vector3.clone() ⇒ Vector3

Clone the vector.

Kind: instance method of Vector3
Returns: Vector3 - cloned vector.

vector3.set(x, y, z) ⇒ Vector3

Set vector value.

Kind: instance method of Vector3
Returns: Vector3 - this.

Param Type Description
x Number X component.
y Number Y component.
z Number Z component.

vector3.copy() ⇒ Vector3

Copy values from other vector into self.

Kind: instance method of Vector3
Returns: Vector3 - this.

vector3.add(Other) ⇒ Vector3

Return a new vector of this + other.

Kind: instance method of Vector3
Returns: Vector3 - result vector.

Param Type Description
Other Number | Vector3 Vector3 or number to add to all components.

vector3.sub(Other) ⇒ Vector3

Return a new vector of this - other.

Kind: instance method of Vector3
Returns: Vector3 - result vector.

Param Type Description
Other Number | Vector3 Vector3 or number to sub from all components.

vector3.div(Other) ⇒ Vector3

Return a new vector of this / other.

Kind: instance method of Vector3
Returns: Vector3 - result vector.

Param Type Description
Other Number | Vector3 Vector3 or number to divide by all components.

vector3.mul(Other) ⇒ Vector3

Return a new vector of this * other.

Kind: instance method of Vector3
Returns: Vector3 - result vector.

Param Type Description
Other Number | Vector3 Vector3 or number to multiply with all components.

vector3.round() ⇒ Vector3

Return a round copy of this vector.

Kind: instance method of Vector3
Returns: Vector3 - result vector.

vector3.floor() ⇒ Vector3

Return a floored copy of this vector.

Kind: instance method of Vector3
Returns: Vector3 - result vector.

vector3.ceil() ⇒ Vector3

Return a ceiled copy of this vector.

Kind: instance method of Vector3
Returns: Vector3 - result vector.

vector3.normalized() ⇒ Vector3

Return a normalized copy of this vector.

Kind: instance method of Vector3
Returns: Vector3 - result vector.

vector3.addSelf(Other) ⇒ Vector3

Add other vector values to self.

Kind: instance method of Vector3
Returns: Vector3 - this.

Param Type Description
Other Number | Vector3 Vector or number to add.

vector3.subSelf(Other) ⇒ Vector3

Sub other vector values from self.

Kind: instance method of Vector3
Returns: Vector3 - this.

Param Type Description
Other Number | Vector3 Vector or number to substract.

vector3.divSelf(Other) ⇒ Vector3

Divide this vector by other vector values.

Kind: instance method of Vector3
Returns: Vector3 - this.

Param Type Description
Other Number | Vector3 Vector or number to divide by.

vector3.mulSelf(Other) ⇒ Vector3

Multiply this vector by other vector values.

Kind: instance method of Vector3
Returns: Vector3 - this.

Param Type Description
Other Number | Vector3 Vector or number to multiply by.

vector3.roundSelf() ⇒ Vector3

Round self.

Kind: instance method of Vector3
Returns: Vector3 - this.

vector3.floorSelf() ⇒ Vector3

Floor self.

Kind: instance method of Vector3
Returns: Vector3 - this.

vector3.ceilSelf() ⇒ Vector3

Ceil self.

Kind: instance method of Vector3
Returns: Vector3 - this.

vector3.normalizeSelf() ⇒ Vector3

Return a normalized copy of this vector.

Kind: instance method of Vector3
Returns: Vector3 - this.

vector3.equals(other) ⇒ Boolean

Return if vector equals another vector.

Kind: instance method of Vector3
Returns: Boolean - if vectors are equal.

Param Type Description
other Vector3 Other vector to compare to.

vector3.approximate(other, threshold) ⇒ Boolean

Return if vector approximately equals another vector.

Kind: instance method of Vector3
Returns: Boolean - if vectors are equal.

Param Type Description
other Vector3 Other vector to compare to.
threshold Number Distance threshold to consider as equal. Defaults to 1.

vector3.length() ⇒ Number

Return vector length (aka magnitude).

Kind: instance method of Vector3
Returns: Number - Vector length.

vector3.scaled() ⇒ Vector3

Return a copy of this vector multiplied by a factor.

Kind: instance method of Vector3
Returns: Vector3 - result vector.

vector3.distanceTo(other) ⇒ Number

Calculate distance between this vector and another vector.

Kind: instance method of Vector3
Returns: Number - Distance between vectors.

Param Type Description
other Vector3 Other vector.

vector3.distanceToSquared(other) ⇒ Number

Calculate squared distance between this vector and another vector.

Kind: instance method of Vector3
Returns: Number - Distance between vectors.

Param Type Description
other Vector3 Other vector.

vector3.clamp(min, max) ⇒ Vector3

Return a clone and clamp its values to be between min and max.

Kind: instance method of Vector3
Returns: Vector3 - Clamped vector.

Param Type Description
min Vector3 Min vector.
max Vector3 Max vector.

vector3.clampSelf(min, max) ⇒ Vector3

Clamp this vector values to be between min and max.

Kind: instance method of Vector3
Returns: Vector3 - Self.

Param Type Description
min Vector3 Min vector.
max Vector3 Max vector.

vector3.dot(other) ⇒ Number

Calculate the dot product with another vector.

Kind: instance method of Vector3
Returns: Number - Dot product value.

Param Type Description
other Vector3 Vector to calculate dot with.

vector3.minSelf(v) ⇒ Vector3

Set self values to be min values between self and a given vector.

Kind: instance method of Vector3
Returns: Vector3 - Self.

Param Type Description
v Vector3 Vector to min with.

vector3.maxSelf(v) ⇒ Vector3

Set self values to be max values between self and a given vector.

Kind: instance method of Vector3
Returns: Vector3 - Self.

Param Type Description
v Vector3 Vector to max with.

vector3.min(v) ⇒ Vector3

Create a clone vector that is the min result between self and a given vector.

Kind: instance method of Vector3
Returns: Vector3 - Result vector.

Param Type Description
v Vector3 Vector to min with.

vector3.max(v) ⇒ Vector3

Create a clone vector that is the max result between self and a given vector.

Kind: instance method of Vector3
Returns: Vector3 - Result vector.

Param Type Description
v Vector3 Vector to max with.

vector3.string()

Convert to string.

Kind: instance method of Vector3

vector3.toArray() ⇒ Array.<Number>

Convert to array of numbers.

Kind: instance method of Vector3
Returns: Array.<Number> - Vector components as array.

vector3.toDict(minimized) ⇒ \*

Convert to dictionary.

Kind: instance method of Vector3
Returns: \* - Dictionary with {x,y,z}

Param Type Description
minimized Boolean If true, will not include keys that their values are 0. You can use fromDict on minimized dicts.

Vector3.zero() ⇒ Vector3

Get vector with 0,0,0 values.

Kind: static method of Vector3
Returns: Vector3 - result vector.

Vector3.one() ⇒ Vector3

Get vector with 1,1,1 values.

Kind: static method of Vector3
Returns: Vector3 - result vector.

Vector3.half() ⇒ Vector3

Get vector with 0.5,0.5 values.

Kind: static method of Vector3
Returns: Vector3 - result vector.

Vector3.left() ⇒ Vector3

Get vector with -1,0,0 values.

Kind: static method of Vector3
Returns: Vector3 - result vector.

Vector3.right() ⇒ Vector3

Get vector with 1,0,0 values.

Kind: static method of Vector3
Returns: Vector3 - result vector.

Vector3.up() ⇒ Vector3

Get vector with 0,-1,0 values.

Kind: static method of Vector3
Returns: Vector3 - result vector.

Vector3.down() ⇒ Vector3

Get vector with 0,1,0 values.

Kind: static method of Vector3
Returns: Vector3 - result vector.

Vector3.front() ⇒ Vector3

Get vector with 0,0,1 values.

Kind: static method of Vector3
Returns: Vector3 - result vector.

Vector3.back() ⇒ Vector3

Get vector with 0,0,-1 values.

Kind: static method of Vector3
Returns: Vector3 - result vector.

Vector3.lerp(p1, p2, a) ⇒ Vector3

Lerp between two vectors.

Kind: static method of Vector3
Returns: Vector3 - result vector.

Param Type Description
p1 Vector3 First vector.
p2 Vector3 Second vector.
a Number Lerp factor (0.0 - 1.0).

Vector3.distance(p1, p2) ⇒ Number

Calculate distance between two vectors.

Kind: static method of Vector3
Returns: Number - Distance between vectors.

Param Type Description
p1 Vector3 First vector.
p2 Vector3 Second vector.

Vector3.crossVector(p1, p2) ⇒ Vector3

Return cross product between two vectors.

Kind: static method of Vector3
Returns: Vector3 - Crossed vector.

Param Type Description
p1 Vector3 First vector.
p2 Vector3 Second vector.

Vector3.parse(str) ⇒ Vector3

Parse and return a vector object from string in the form of “x,y”.

Kind: static method of Vector3
Returns: Vector3 - Parsed vector.

Param Type Description
str String String to parse.

Vector3.fromArray(arr) ⇒ Vector3

Create vector from array of numbers.

Kind: static method of Vector3
Returns: Vector3 - Vector instance.

Param Type Description
arr Array.<Number> Array of numbers to create vector from.

Vector3.fromDict(data) ⇒ Vector3

Create vector from a dictionary.

Kind: static method of Vector3
Returns: Vector3 - Newly created vector.

Param Type Description
data \* Dictionary with {x,y,z}.

BlendMode : String

Kind: global typedef

BuffersUsage : String

Kind: global typedef

UniformType : String

Kind: global typedef

TextAlignment : String

Kind: global typedef

TextureFilterMode : String

Kind: global typedef

TextureWrapMode : String

Kind: global typedef

MouseButton : Number

Kind: global typedef

KeyboardKey : Number

Kind: global typedef