API Reference

Class List

pc.Application

Extends: pc.EventHandler

A pc.Application represents and manages your PlayCanvas application. If you are developing using the PlayCanvas Editor, the pc.Application is created for you. You can access your pc.Application instance in your scripts. Below is a skeleton script which shows how you can access the application 'app' property inside the initialize and update functions:

// Editor example: accessing the pc.Application from a script
var MyScript = pc.createScript('myScript');

MyScript.prototype.initialize = function() {
    // Every script instance has a property 'this.app' accessible in the initialize...
    var app = this.app;
};

MyScript.prototype.update = function(dt) {
    // ...and update functions.
    var app = this.app;
};

If you are using the Engine without the Editor, you have to create the application instance manually.

// Engine-only example: create the application manually
var app = new pc.Application(canvas, options);

// Start the application's main loop
app.start();

Summary

Static Methods

getApplication

Get the current application.

Properties

assets

The asset registry managed by the application.

autoRender

When true, the application's render function is called every frame.

batcher

The application's batch manager.

elementInput

Used to handle input for pc.ElementComponents.

fillMode

The current fill mode of the canvas.[read only]

gamepads

Used to access GamePad input.

graphicsDevice

The graphics device used by the application.

i18n

Handles localization.

keyboard

The keyboard device.

loader

The resource loader.

maxDeltaTime

Clamps per-frame delta time to an upper bound.

mouse

The mouse device.

renderNextFrame

Set to true to render the scene on the next iteration of the main loop.

resolutionMode

The current resolution mode of the canvas, Can be:

  • pc.RESOLUTION_AUTO: if width and height are not provided, canvas will be resized to match canvas client size.[read only]
root

The root entity of the application.

scene

The scene managed by the application.

scenes

The scene registry managed by the application.

scripts

The application's script registry.

systems

The application's component system registry.

timeScale

Scales the global time delta.

touch

Used to get touch events input.

xr

The XR Manager that provides ability to start VR/AR sessions.

Methods

applySceneSettings

Apply scene settings to the current scene.

configure

Load the application configuration file and apply application properties and fill the asset registry.

destroy

Destroys application and removes all event listeners.

isHidden

Queries the visibility of the window or tab in which the application is running.

preload

Load all assets in the asset registry that are marked as 'preload'.

render

Render the application's scene.

renderLine

Renders a line.

renderLines

Renders an arbitrary number of discrete line segments.

resizeCanvas

Resize the application's canvas element in line with the current fill mode.

setCanvasFillMode

Controls how the canvas fills the window and resizes when the window changes.

setCanvasResolution

Change the resolution of the canvas, and set the way it behaves when the window is resized.

setSkybox

Sets the skybox asset to current scene, and subscribes to asset load/change events.

start

Start the application.

update

Update the application.

Inherited

Methods

fire

Fire an event, all additional arguments are passed on to the event listener.

hasEvent

Test if there are any handlers bound to an event name.

off

Detach an event handler from an event.

on

Attach an event handler to an event.

once

Attach an event handler to an event.

Details

Static Methods

getApplication([id])

Get the current application. In the case where there are multiple running applications, the function can get an application based on a supplied canvas id. This function is particularly useful when the current pc.Application is not readily available. For example, in the JavaScript console of the browser's developer tools.

var app = pc.Application.getApplication();

Parameters

idstring

If defined, the returned application should use the canvas which has this id. Otherwise current application will be returned.

Returns

pc.Application, undefined

The running application, if any.

Constructor

Application(canvas, options)

Create a new Application.

// Engine-only example: create the application manually
var app = new pc.Application(canvas, options);

// Start the application's main loop
app.start();

Parameters

canvasElement

The canvas element.

optionsobject
options.elementInputpc.ElementInput

Input handler for pc.ElementComponents.

options.keyboardpc.Keyboard

Keyboard handler for input.

options.mousepc.Mouse

Mouse handler for input.

options.touchpc.TouchDevice

TouchDevice handler for input.

options.gamepadspc.GamePads

Gamepad handler for input.

options.scriptPrefixstring

Prefix to apply to script urls before loading.

options.assetPrefixstring

Prefix to apply to asset urls before loading.

options.graphicsDeviceOptionsobject

Options object that is passed into the pc.GraphicsDevice constructor.

options.scriptsOrderstring[]

Scripts in order of loading first.

Properties

pc.AssetRegistryassets

The asset registry managed by the application.

// Search the asset registry for all assets with the tag 'vehicle'
var vehicleAssets = this.app.assets.findByTag('vehicle');
booleanautoRender

When true, the application's render function is called every frame. Setting autoRender to false is useful to applications where the rendered image may often be unchanged over time. This can heavily reduce the application's load on the CPU and GPU. Defaults to true.

// Disable rendering every frame and only render on a keydown event
this.app.autoRender = false;
this.app.keyboard.on('keydown', function (event) {
    this.app.renderNextFrame = true;
}, this);
pc.BatchManagerbatcher

The application's batch manager. The batch manager is used to merge mesh instances in the scene, which reduces the overall number of draw calls, thereby boosting performance.

pc.ElementInputelementInput

Used to handle input for pc.ElementComponents.

stringfillMode

The current fill mode of the canvas. Can be:

[read only]

pc.GamePadsgamepads

Used to access GamePad input.

pc.GraphicsDevicegraphicsDevice

The graphics device used by the application.

pc.I18ni18n

Handles localization.

pc.Keyboardkeyboard

The keyboard device.

pc.ResourceLoaderloader

The resource loader.

numbermaxDeltaTime

Clamps per-frame delta time to an upper bound. Useful since returning from a tab deactivation can generate huge values for dt, which can adversely affect game state. Defaults to 0.1 (seconds).

// Don't clamp inter-frame times of 200ms or less
this.app.maxDeltaTime = 0.2;
pc.Mousemouse

The mouse device.

booleanrenderNextFrame

Set to true to render the scene on the next iteration of the main loop. This only has an effect if pc.Application#autoRender is set to false. The value of renderNextFrame is set back to false again as soon as the scene has been rendered.

// Render the scene only while space key is pressed
if (this.app.keyboard.isPressed(pc.KEY_SPACE)) {
    this.app.renderNextFrame = true;
}
stringresolutionMode

The current resolution mode of the canvas, Can be:

[read only]

pc.Entityroot

The root entity of the application.

// Return the first entity called 'Camera' in a depth-first search of the scene hierarchy
var camera = this.app.root.findByName('Camera');
pc.Scenescene

The scene managed by the application.

// Set the tone mapping property of the application's scene
this.app.scene.toneMapping = pc.TONEMAP_FILMIC;
pc.SceneRegistryscenes

The scene registry managed by the application.

// Search the scene registry for a item with the name 'racetrack1'
var sceneItem = this.app.scenes.find('racetrack1');

// Load the scene using the item's url
this.app.scenes.loadScene(sceneItem.url);
pc.ScriptRegistryscripts

The application's script registry.

pc.ComponentSystemRegistrysystems

The application's component system registry. The pc.Application constructor adds the following component systems to its component system registry:

// Set global gravity to zero
this.app.systems.rigidbody.gravity.set(0, 0, 0);
// Set the global sound volume to 50%
this.app.systems.sound.volume = 0.5;
numbertimeScale

Scales the global time delta. Defaults to 1.

// Set the app to run at half speed
this.app.timeScale = 0.5;
pc.TouchDevicetouch

Used to get touch events input.

pc.XrManagerxr

The XR Manager that provides ability to start VR/AR sessions.

// check if VR is available
if (app.xr.isAvailable(pc.XRTYPE_VR)) {
    // VR is available
}

Methods

applySceneSettings(settings)

Apply scene settings to the current scene. Useful when your scene settings are parsed or generated from a non-URL source.

var settings = {
    physics: {
        gravity: [0, -9.8, 0]
    },
    render: {
        fog_end: 1000,
        tonemapping: 0,
        skybox: null,
        fog_density: 0.01,
        gamma_correction: 1,
        exposure: 1,
        fog_start: 1,
        global_ambient: [0, 0, 0],
        skyboxIntensity: 1,
        fog_color: [0, 0, 0],
        lightmapMode: 1,
        fog: 'none',
        lightmapMaxResolution: 2048,
        skyboxMip: 2,
        lightmapSizeMultiplier: 16
    }
};
app.applySceneSettings(settings);

Parameters

settingsobject

The scene settings to be applied.

settings.physicsobject

The physics settings to be applied.

settings.physics.gravitynumber[]

The world space vector representing global gravity in the physics simulation. Must be a fixed size array with three number elements, corresponding to each axis [ X, Y, Z ].

settings.renderobject

The rendering settings to be applied.

settings.render.global_ambientnumber[]

The color of the scene's ambient light. Must be a fixed size array with three number elements, corresponding to each color channel [ R, G, B ].

settings.render.fogstring

The type of fog used by the scene. Can be:

settings.render.fog_colornumber[]

The color of the fog (if enabled). Must be a fixed size array with three number elements, corresponding to each color channel [ R, G, B ].

settings.render.fog_densitynumber

The density of the fog (if enabled). This property is only valid if the fog property is set to pc.FOG_EXP or pc.FOG_EXP2.

settings.render.fog_startnumber

The distance from the viewpoint where linear fog begins. This property is only valid if the fog property is set to pc.FOG_LINEAR.

settings.render.fog_endnumber

The distance from the viewpoint where linear fog reaches its maximum. This property is only valid if the fog property is set to pc.FOG_LINEAR.

settings.render.gamma_correctionnumber

The gamma correction to apply when rendering the scene. Can be:

settings.render.tonemappingnumber

The tonemapping transform to apply when writing fragments to the frame buffer. Can be:

settings.render.exposurenumber

The exposure value tweaks the overall brightness of the scene.

settings.render.skyboxnumber, null

The asset ID of the cube map texture to be used as the scene's skybox. Defaults to null.

settings.render.skyboxIntensitynumber

Multiplier for skybox intensity.

settings.render.skyboxMipnumber

The mip level of the skybox to be displayed. Only valid for prefiltered cubemap skyboxes.

settings.render.lightmapSizeMultipliernumber

The lightmap resolution multiplier.

settings.render.lightmapMaxResolutionnumber

The maximum lightmap resolution.

settings.render.lightmapModenumber

The lightmap baking mode. Can be:

Only lights with bakeDir=true will be used for generating the dominant light direction. Defaults to.

configure(url, callback)

Load the application configuration file and apply application properties and fill the asset registry.

Parameters

urlstring

The URL of the configuration file to load.

callbackpc.callbacks.ConfigureApp

The Function called when the configuration file is loaded and parsed (or an error occurs).

destroy()

Destroys application and removes all event listeners.

this.app.destroy();

isHidden()

Queries the visibility of the window or tab in which the application is running.

Returns

boolean

True if the application is not visible and false otherwise.

preload(callback)

Load all assets in the asset registry that are marked as 'preload'.

Parameters

callbackpc.callbacks.PreloadApp

Function called when all assets are loaded.

render()

Render the application's scene. More specifically, the scene's pc.LayerComposition is rendered by the application's pc.ForwardRenderer. This function is called internally in the application's main loop and does not need to be called explicitly.

renderLine(start, end, color, [endColor], [options])

Renders a line. Line start and end coordinates are specified in world-space. If a single color is supplied, the line will be flat-shaded with that color. If two colors are supplied, the line will be smooth shaded between those colors. It is also possible to control which scene layer the line is rendered into. By default, lines are rendered into the immediate layer pc.LAYERID_IMMEDIATE.

// Render a 1-unit long white line
var start = new pc.Vec3(0, 0, 0);
var end = new pc.Vec3(1, 0, 0);
var color = new pc.Color(1, 1, 1);
app.renderLine(start, end, color);
// Render a 1-unit long line that is smooth-shaded from white to red
var start = new pc.Vec3(0, 0, 0);
var end = new pc.Vec3(1, 0, 0);
var startColor = new pc.Color(1, 1, 1);
var endColor = new pc.Color(1, 0, 0);
app.renderLine(start, end, startColor, endColor);
// Render a 1-unit long white line into the world layer
var start = new pc.Vec3(0, 0, 0);
var end = new pc.Vec3(1, 0, 0);
var color = new pc.Color(1, 1, 1);
var worldLayer = app.scene.layers.getLayerById(pc.LAYERID_WORLD);
app.renderLine(start, end, color, {
    layer: worldLayer
});
// Render a 1-unit long line that is smooth-shaded from white to red into the world layer
var start = new pc.Vec3(0, 0, 0);
var end = new pc.Vec3(1, 0, 0);
var startColor = new pc.Color(1, 1, 1);
var endColor = new pc.Color(1, 0, 0);
var worldLayer = app.scene.layers.getLayerById(pc.LAYERID_WORLD);
app.renderLine(start, end, color, {
    layer: worldLayer
});

Parameters

startpc.Vec3

The start world-space coordinate of the line.

endpc.Vec3

The end world-space coordinate of the line.

colorpc.Color

The start color of the line.

endColorpc.Color

The end color of the line.

optionsobject

Options to set rendering properties.

options.layerpc.Layer

The layer to render the line into. Defaults to pc.LAYERID_IMMEDIATE.

renderLines(position, color, [options])

Renders an arbitrary number of discrete line segments. The lines are not connected by each subsequent point in the array. Instead, they are individual segments specified by two points. Therefore, the lengths of the supplied position and color arrays must be the same and also must be a multiple of 2. The colors of the ends of each line segment will be interpolated along the length of each line.

// Render 2 discrete line segments
var points = [
    // Line 1
    new pc.Vec3(0, 0, 0),
    new pc.Vec3(1, 0, 0),
    // Line 2
    new pc.Vec3(1, 1, 0),
    new pc.Vec3(1, 1, 1)
];
var colors = [
    // Line 1
    pc.Color.RED,
    pc.Color.YELLOW,
    // Line 2
    pc.Color.CYAN,
    pc.Color.BLUE
];
app.renderLines(points, colors);

Parameters

positionpc.Vec3[]

An array of points to draw lines between. The length of the array must be a multiple of 2.

colorpc.Color[]

An array of colors to color the lines. This must be the same length as the position array. The length of the array must also be a multiple of 2.

optionsobject

Options to set rendering properties.

options.layerpc.Layer

The layer to render the lines into.

resizeCanvas([width], [height])

Resize the application's canvas element in line with the current fill mode. In pc.FILLMODE_KEEP_ASPECT mode, the canvas will grow to fill the window as best it can while maintaining the aspect ratio. In pc.FILLMODE_FILL_WINDOW mode, the canvas will simply fill the window, changing aspect ratio. In pc.FILLMODE_NONE mode, the canvas will always match the size provided.

Parameters

widthnumber

The width of the canvas. Only used if current fill mode is pc.FILLMODE_NONE.

heightnumber

The height of the canvas. Only used if current fill mode is pc.FILLMODE_NONE.

Returns

object

A object containing the values calculated to use as width and height.

setCanvasFillMode(mode, [width], [height])

Controls how the canvas fills the window and resizes when the window changes.

Parameters

modestring

The mode to use when setting the size of the canvas. Can be:

widthnumber

The width of the canvas (only used when mode is pc.FILLMODE_NONE).

heightnumber

The height of the canvas (only used when mode is pc.FILLMODE_NONE).

setCanvasResolution(mode, [width], [height])

Change the resolution of the canvas, and set the way it behaves when the window is resized.

Parameters

modestring

The mode to use when setting the resolution. Can be:

widthnumber

The horizontal resolution, optional in AUTO mode, if not provided canvas clientWidth is used.

heightnumber

The vertical resolution, optional in AUTO mode, if not provided canvas clientHeight is used.

setSkybox(asset)

Sets the skybox asset to current scene, and subscribes to asset load/change events.

Parameters

assetpc.Asset

Asset of type skybox to be set to, or null to remove skybox.

start()

Start the application. This function does the following:

  1. Fires an event on the application named 'start'
  2. Calls initialize for all components on entities in the hierarchy
  3. Fires an event on the application named 'initialize'
  4. Calls postInitialize for all components on entities in the hierarchy
  5. Fires an event on the application named 'postinitialize'
  6. Starts executing the main loop of the application This function is called internally by PlayCanvas applications made in the Editor but you will need to call start yourself if you are using the engine stand-alone.

app.start();

update(dt)

Update the application. This function will call the update functions and then the postUpdate functions of all enabled components. It will then update the current state of all connected input devices. This function is called internally in the application's main loop and does not need to be called explicitly.

Parameters

dtnumber

The time delta since the last frame.

Inherited

Methods

fire(name, [arg1], [arg2], [arg3], [arg4], [arg5], [arg6], [arg7], [arg8])

Fire an event, all additional arguments are passed on to the event listener.

obj.fire('test', 'This is the message');

Parameters

nameobject

Name of event to fire.

arg1*

First argument that is passed to the event handler.

arg2*

Second argument that is passed to the event handler.

arg3*

Third argument that is passed to the event handler.

arg4*

Fourth argument that is passed to the event handler.

arg5*

Fifth argument that is passed to the event handler.

arg6*

Sixth argument that is passed to the event handler.

arg7*

Seventh argument that is passed to the event handler.

arg8*

Eighth argument that is passed to the event handler.

Returns

pc.EventHandler

Self for chaining.

hasEvent(name)

Test if there are any handlers bound to an event name.

obj.on('test', function () { }); // bind an event to 'test'
obj.hasEvent('test'); // returns true
obj.hasEvent('hello'); // returns false

Parameters

namestring

The name of the event to test.

Returns

boolean

True if the object has handlers bound to the specified event name.

off([name], [callback], [scope])

Detach an event handler from an event. If callback is not provided then all callbacks are unbound from the event, if scope is not provided then all events with the callback will be unbound.

var handler = function () {
};
obj.on('test', handler);

obj.off(); // Removes all events
obj.off('test'); // Removes all events called 'test'
obj.off('test', handler); // Removes all handler functions, called 'test'
obj.off('test', handler, this); // Removes all hander functions, called 'test' with scope this

Parameters

namestring

Name of the event to unbind.

callbackpc.callbacks.HandleEvent

Function to be unbound.

scopeobject

Scope that was used as the this when the event is fired.

Returns

pc.EventHandler

Self for chaining.

on(name, callback, [scope])

Attach an event handler to an event.

obj.on('test', function (a, b) {
    console.log(a + b);
});
obj.fire('test', 1, 2); // prints 3 to the console

Parameters

namestring

Name of the event to bind the callback to.

callbackpc.callbacks.HandleEvent

Function that is called when event is fired. Note the callback is limited to 8 arguments.

scopeobject

Object to use as 'this' when the event is fired, defaults to current this.

Returns

pc.EventHandler

Self for chaining.

once(name, callback, [scope])

Attach an event handler to an event. This handler will be removed after being fired once.

obj.once('test', function (a, b) {
    console.log(a + b);
});
obj.fire('test', 1, 2); // prints 3 to the console
obj.fire('test', 1, 2); // not going to get handled

Parameters

namestring

Name of the event to bind the callback to.

callbackpc.callbacks.HandleEvent

Function that is called when event is fired. Note the callback is limited to 8 arguments.

scopeobject

Object to use as 'this' when the event is fired, defaults to current this.

Returns

pc.EventHandler

Self for chaining.