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

getApplicationGet the current application.

Properties

assetsThe asset registry managed by the application.
autoRenderWhen true, the application's render function is called every frame.
batcherThe application's batch manager.
elementInputUsed to handle input for pc.ElementComponents.
gamepadsUsed to access GamePad input.
graphicsDeviceThe graphics device used by the application.
i18nHandles localization
keyboardThe keyboard device.
loaderThe resource loader.
maxDeltaTimeClamps per-frame delta time to an upper bound.
mouseThe mouse device.
renderNextFrameSet to true to render the scene on the next iteration of the main loop.
rootThe root entity of the application.
sceneThe scene managed by the application.
scriptsThe application's script registry.
systemsThe application's component system registry.
timeScaleScales the global time delta.
touchUsed to get touch events input.

Methods

applySceneSettingsApply scene settings to the current scene.
configureLoad the application configuration file and apply application properties and fill the asset registry
destroyDestroys application and removes all event listeners.
disableVrDestroy the pc.VrManager
enableVrCreate and assign a pc.VrManager object to allow this application render in VR.
getSceneUrlLook up the URL of the scene hierarchy file via the name given to the scene in the editor.
isHiddenQueries the visibility of the window or tab in which the application is running.
loadSceneHierarchyLoad a scene file, create and initialize the Entity hierarchy and add the hierarchy to the application root Entity.
loadSceneSettingsLoad a scene file and automatically apply the scene settings to the current scene.
preloadLoad all assets in the asset registry that are marked as 'preload'
renderRender the application's scene.
renderLineRenders a line.
renderLinesDraw an array of lines.
resizeCanvasResize the application's canvas element in line with the current fill mode.
setCanvasFillModeControls how the canvas fills the window and resizes when the window changes.
setCanvasResolutionChange the resolution of the canvas, and set the way it behaves when the window is resized
setSkyboxSets the skybox asset to current scene, and subscribes to asset load/change events
startStart the application.
updateUpdate the application.

Inherited

Methods

fireFire an event, all additional arguments are passed on to the event listener
hasEventTest if there are any handlers bound to an event name
offDetach an event handler from an event.
onAttach an event handler to an event
onceAttach 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

idStringIf 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

canvasElementThe canvas element
optionsObject
options.elementInputpc.ElementInputInput handler for pc.ElementComponents
options.keyboardpc.KeyboardKeyboard handler for input
options.mousepc.MouseMouse handler for input
options.touchpc.TouchDeviceTouchDevice handler for input
options.gamepadspc.GamePadsGamepad handler for input
options.scriptPrefixStringPrefix to apply to script urls before loading
options.assetPrefixStringPrefix to apply to asset urls before loading
options.graphicsDeviceOptionsObjectOptions 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.

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;
}
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.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.

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

settingsObjectThe scene settings to be applied.
settings.physicsObjectThe 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.renderObjectThe 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.fogStringThe type of fog used by the scene. Can be:
  • pc.FOG_NONE
  • pc.FOG_LINEAR
  • pc.FOG_EXP
  • pc.FOG_EXP2
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_densityNumberThe 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_startNumberThe 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_endNumberThe 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_correctionNumberThe gamma correction to apply when rendering the scene. Can be:
  • pc.GAMMA_NONE
  • pc.GAMMA_SRGB
settings.render.tonemappingNumberThe tonemapping transform to apply when writing fragments to the frame buffer. Can be:
  • pc.TONEMAP_LINEAR
  • pc.TONEMAP_FILMIC
  • pc.TONEMAP_HEJL
  • pc.TONEMAP_ACES
settings.render.exposureNumberThe exposure value tweaks the overall brightness of the scene.
settings.render.skyboxNumber, NullThe asset ID of the cube map texture to be used as the scene's skybox. Defaults to null.
settings.render.skyboxIntensityNumberMultiplier for skybox intensity.
settings.render.skyboxMipNumberThe mip level of the skybox to be displayed. Only valid for prefiltered cubemap skyboxes.
settings.render.lightmapSizeMultiplierNumberThe lightmap resolution multiplier.
settings.render.lightmapMaxResolutionNumberThe maximum lightmap resolution.
settings.render.lightmapModeNumberThe lightmap baking mode. Can be:
  • pc.BAKE_COLOR: single color lightmap
  • pc.BAKE_COLORDIR: single color lightmap + dominant light direction (used for bump/specular)
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

urlStringThe URL of the configuration file to load
callbackpc.callbacks.ConfigureAppThe 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();

disableVr()

Destroy the pc.VrManager

enableVr()

Create and assign a pc.VrManager object to allow this application render in VR.

getSceneUrl(name)

Look up the URL of the scene hierarchy file via the name given to the scene in the editor. Use this to in pc.Application#loadSceneHierarchy.

Parameters

nameStringThe name of the scene file given in the Editor

Returns

String The URL of the scene file

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.

loadSceneHierarchy(url, callback)

Load a scene file, create and initialize the Entity hierarchy and add the hierarchy to the application root Entity.

app.loadSceneHierarchy("1000.json", function (err, entity) {
    if (!err) {
      var e = app.root.find("My New Entity");
    } else {
      // error
    }
  }
});

Parameters

urlStringThe URL of the scene file. Usually this will be "scene_id.json"
callbackpc.callbacks.LoadHierarchyThe function to call after loading, passed (err, entity) where err is null if no errors occurred.

loadSceneSettings(url, callback)

Load a scene file and automatically apply the scene settings to the current scene.

app.loadSceneSettings("1000.json", function (err) {
    if (!err) {
      // success
    } else {
      // error
    }
  }
});

Parameters

urlStringThe URL of the scene file. Usually this will be "scene_id.json"
callbackpc.callbacks.LoadSettingsThe function called after the settings are applied. Passed (err) where err is null if no error occurred.

preload(callback)

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

Parameters

callbackpc.callbacks.PreloadAppFunction 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.Vec3The start world-space coordinate of the line.
endpc.Vec3The end world-space coordinate of the line.
colorpc.ColorThe start color of the line.
endColorpc.ColorThe end color of the line.
optionsObjectOptions to set rendering properties
options.layerpc.LayerThe layer to render the line into. Defaults to pc.LAYERID_IMMEDIATE.

renderLines(position, color, [options])

Draw an array of lines.

var points = [new pc.Vec3(0,0,0), new pc.Vec3(1,0,0), new pc.Vec3(1,1,0), new pc.Vec3(1,1,1)];
var colors = [new pc.Color(1,0,0), new pc.Color(1,1,0), new pc.Color(0,1,1), new pc.Color(0,0,1)];
app.renderLines(points, colors);

Parameters

positionpc.Vec3[]An array of points to draw lines between
colorpc.Color[]An array of colors to color the lines. This must be the same size as the position array
optionsObjectOptions to set rendering properties
options.layerpc.LayerThe layer to render the line 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

widthNumberThe width of the canvas. Only used if current fill mode is pc.FILLMODE_NONE.
heightNumberThe 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

modeStringThe mode to use when setting the size of the canvas. Can be:
  • pc.FILLMODE_NONE: the canvas will always match the size provided.
  • pc.FILLMODE_FILL_WINDOW: the canvas will simply fill the window, changing aspect ratio.
  • pc.FILLMODE_KEEP_ASPECT: the canvas will grow to fill the window as best it can while maintaining the aspect ratio.
widthNumberThe width of the canvas (only used when mode is pc.FILLMODE_NONE).
heightNumberThe 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

modeStringThe mode to use when setting the resolution. Can be:
  • pc.RESOLUTION_AUTO: if width and height are not provided, canvas will be resized to match canvas client size.
  • pc.RESOLUTION_FIXED: resolution of canvas will be fixed.
widthNumberThe horizontal resolution, optional in AUTO mode, if not provided canvas clientWidth is used
heightNumberThe 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.AssetAsset 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 hierachy
  3. Fires an event on the application named 'initialize'
  4. Calls postInitialize for all components on entities in the hierachy
  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

dtNumberThe 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

nameObjectName 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

nameStringThe 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

nameStringName of the event to unbind
callbackpc.callbacks.HandleEventFunction to be unbound.
scopeObjectScope 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

nameStringName of the event to bind the callback to
callbackpc.callbacks.HandleEventFunction that is called when event is fired. Note the callback is limited to 8 arguments.
scopeObjectObject 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

nameStringName of the event to bind the callback to
callbackpc.callbacks.HandleEventFunction that is called when event is fired. Note the callback is limited to 8 arguments.
scopeObjectObject to use as 'this' when the event is fired, defaults to current this

Returns

pc.EventHandler Self for chaining.