An Application represents and manages your PlayCanvas application. If you are developing using the PlayCanvas Editor, the Application is created for you. You can access your 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...
const app = this.app;
};

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

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

Hierarchy (view full)

Constructors

Properties

The asset registry managed by the application.

// Search the asset registry for all assets with the tag 'vehicle'
const vehicleAssets = this.app.assets.findByTag('vehicle');
autoRender: boolean

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);
elementInput: ElementInput

Used to handle input for ElementComponents.

gamepads: GamePads

Used to access GamePad input.

graphicsDevice: GraphicsDevice

The graphics device used by the application.

i18n: I18n

Handles localization.

keyboard: Keyboard

The keyboard device.

lightmapper: Lightmapper

The run-time lightmapper.

The resource loader.

maxDeltaTime: number

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;
mouse: Mouse

The mouse device.

renderNextFrame: boolean

Set to true to render the scene on the next iteration of the main loop. This only has an effect if AppBase#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;
}
root: Entity

The root entity of the application.

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

The scene managed by the application.

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

The scene registry managed by the application.

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

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

The application's script registry.

The application's component system registry. The 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;
timeScale: number

Scales the global time delta. Defaults to 1.

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

Used to get touch events input.

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
}

Accessors

Methods

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

    Parameters

    • settings: {
          physics: {
              gravity: number[];
          };
          render: {
              ambientBake: boolean;
              ambientBakeNumSamples: number;
              ambientBakeOcclusionBrightness: number;
              ambientBakeOcclusionContrast: number;
              ambientBakeSpherePart: number;
              ambientLuminance: number;
              clusteredLightingEnabled: boolean;
              exposure: number;
              fog: string;
              fog_color: number[];
              fog_density: number;
              fog_end: number;
              fog_start: number;
              gamma_correction: number;
              global_ambient: number[];
              lightingAreaLightsEnabled: boolean;
              lightingCells: Vec3;
              lightingCookieAtlasResolution: number;
              lightingCookiesEnabled: boolean;
              lightingMaxLightsPerCell: number;
              lightingShadowAtlasResolution: number;
              lightingShadowsEnabled: boolean;
              lightingShadowType: number;
              lightmapMaxResolution: number;
              lightmapMode: number;
              lightmapSizeMultiplier: number;
              skybox: number;
              skyboxIntensity: number;
              skyboxLuminance: number;
              skyboxMip: number;
              skyboxRotation: number[];
              tonemapping: number;
          };
      }

      The scene settings to be applied.

      • physics: {
            gravity: number[];
        }

        The physics settings to be applied.

        • gravity: number[]
      • render: {
            ambientBake: boolean;
            ambientBakeNumSamples: number;
            ambientBakeOcclusionBrightness: number;
            ambientBakeOcclusionContrast: number;
            ambientBakeSpherePart: number;
            ambientLuminance: number;
            clusteredLightingEnabled: boolean;
            exposure: number;
            fog: string;
            fog_color: number[];
            fog_density: number;
            fog_end: number;
            fog_start: number;
            gamma_correction: number;
            global_ambient: number[];
            lightingAreaLightsEnabled: boolean;
            lightingCells: Vec3;
            lightingCookieAtlasResolution: number;
            lightingCookiesEnabled: boolean;
            lightingMaxLightsPerCell: number;
            lightingShadowAtlasResolution: number;
            lightingShadowsEnabled: boolean;
            lightingShadowType: number;
            lightmapMaxResolution: number;
            lightmapMode: number;
            lightmapSizeMultiplier: number;
            skybox: number;
            skyboxIntensity: number;
            skyboxLuminance: number;
            skyboxMip: number;
            skyboxRotation: number[];
            tonemapping: number;
        }

        The rendering settings to be applied.

        • ambientBake: boolean
        • ambientBakeNumSamples: number
        • ambientBakeOcclusionBrightness: number
        • ambientBakeOcclusionContrast: number
        • ambientBakeSpherePart: number
        • ambientLuminance: number
        • clusteredLightingEnabled: boolean
        • exposure: number
        • fog: string
        • fog_color: number[]
        • fog_density: number
        • fog_end: number
        • fog_start: number
        • gamma_correction: number
        • global_ambient: number[]
        • lightingAreaLightsEnabled: boolean
        • lightingCells: Vec3
        • lightingCookieAtlasResolution: number
        • lightingCookiesEnabled: boolean
        • lightingMaxLightsPerCell: number
        • lightingShadowAtlasResolution: number
        • lightingShadowsEnabled: boolean
        • lightingShadowType: number
        • lightmapMaxResolution: number
        • lightmapMode: number
        • lightmapSizeMultiplier: number
        • skybox: number
        • skyboxIntensity: number
        • skyboxLuminance: number
        • skyboxMip: number
        • skyboxRotation: number[]
        • tonemapping: number

    Returns void

    const 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,
    skyboxRotation: [0, 0, 0],
    fog_color: [0, 0, 0],
    lightmapMode: 1,
    fog: 'none',
    lightmapMaxResolution: 2048,
    skyboxMip: 2,
    lightmapSizeMultiplier: 16
    }
    };
    app.applySceneSettings(settings);
  • Load the application configuration file and apply application properties and fill the asset registry.

    Parameters

    • url: string

      The URL of the configuration file to load.

    • callback: ConfigureAppCallback

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

    Returns void

  • Destroys application and removes all event listeners at the end of the current engine frame update. However, if called outside of the engine frame update, calling destroy() will destroy the application immediately.

    Returns void

    app.destroy();
    
  • Draws a single line. Line start and end coordinates are specified in world space. The line will be flat-shaded with the specified color.

    Parameters

    • start: Vec3

      The start world space coordinate of the line.

    • end: Vec3

      The end world space coordinate of the line.

    • Optionalcolor: Color

      The color of the line. It defaults to white if not specified.

    • OptionaldepthTest: boolean

      Specifies if the line is depth tested against the depth buffer. Defaults to true.

    • Optionallayer: Layer

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

    Returns void

    // Render a 1-unit long white line
    const start = new pc.Vec3(0, 0, 0);
    const end = new pc.Vec3(1, 0, 0);
    app.drawLine(start, end);
    // Render a 1-unit long red line which is not depth tested and renders on top of other geometry
    const start = new pc.Vec3(0, 0, 0);
    const end = new pc.Vec3(1, 0, 0);
    app.drawLine(start, end, pc.Color.RED, false);
    // Render a 1-unit long white line into the world layer
    const start = new pc.Vec3(0, 0, 0);
    const end = new pc.Vec3(1, 0, 0);
    const worldLayer = app.scene.layers.getLayerById(pc.LAYERID_WORLD);
    app.drawLine(start, end, pc.Color.WHITE, true, worldLayer);
  • 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.

    Parameters

    • positions: number[]

      An array of points to draw lines between. Each point is represented by 3 numbers - x, y and z coordinate.

    • colors: number[] | Color

      A single color for all lines, or an array of colors to color the lines. If an array is specified, number of colors it stores must match the number of positions provided.

    • OptionaldepthTest: boolean = true

      Specifies if the lines are depth tested against the depth buffer. Defaults to true.

    • Optionallayer: Layer = ...

      The layer to render the lines into. Defaults to LAYERID_IMMEDIATE.

    Returns void

    // Render 2 discrete line segments
    const points = [
    // Line 1
    0, 0, 0,
    1, 0, 0,
    // Line 2
    1, 1, 0,
    1, 1, 1
    ];
    const colors = [
    // Line 1
    1, 0, 0, 1, // red
    0, 1, 0, 1, // green
    // Line 2
    0, 0, 1, 1, // blue
    1, 1, 1, 1 // white
    ];
    app.drawLineArrays(points, colors);
  • 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.

    Parameters

    • positions: Vec3[]

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

    • colors: Color | Color[]

      An array of colors or a single color. If an array is specified, this must be the same length as the position array. The length of the array must also be a multiple of 2.

    • OptionaldepthTest: boolean = true

      Specifies if the lines are depth tested against the depth buffer. Defaults to true.

    • Optionallayer: Layer = ...

      The layer to render the lines into. Defaults to LAYERID_IMMEDIATE.

    Returns void

    // Render a single line, with unique colors for each point
    const start = new pc.Vec3(0, 0, 0);
    const end = new pc.Vec3(1, 0, 0);
    app.drawLines([start, end], [pc.Color.RED, pc.Color.WHITE]);
    // Render 2 discrete line segments
    const 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)
    ];
    const colors = [
    // Line 1
    pc.Color.RED,
    pc.Color.YELLOW,
    // Line 2
    pc.Color.CYAN,
    pc.Color.BLUE
    ];
    app.drawLines(points, colors);
  • Fire an event, all additional arguments are passed on to the event listener.

    Parameters

    • name: string

      Name of event to fire.

    • Optionalarg1: any

      First argument that is passed to the event handler.

    • Optionalarg2: any

      Second argument that is passed to the event handler.

    • Optionalarg3: any

      Third argument that is passed to the event handler.

    • Optionalarg4: any

      Fourth argument that is passed to the event handler.

    • Optionalarg5: any

      Fifth argument that is passed to the event handler.

    • Optionalarg6: any

      Sixth argument that is passed to the event handler.

    • Optionalarg7: any

      Seventh argument that is passed to the event handler.

    • Optionalarg8: any

      Eighth argument that is passed to the event handler.

    Returns EventHandler

    Self for chaining.

    obj.fire('test', 'This is the message');
    
  • Test if there are any handlers bound to an event name.

    Parameters

    • name: string

      The name of the event to test.

    Returns boolean

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

    obj.on('test', function () { }); // bind an event to 'test'
    obj.hasEvent('test'); // returns true
    obj.hasEvent('hello'); // returns false
  • 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.

    Parameters

    • Optionalname: string

      Name of the event to unbind.

    • Optionalcallback: HandleEventCallback

      Function to be unbound.

    • Optionalscope: object

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

    Returns EventHandler

    Self for chaining.

    const 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 handler functions, called 'test' with scope this
  • Attach an event handler to an event.

    Parameters

    • name: string

      Name of the event to bind the callback to.

    • callback: HandleEventCallback

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

    • Optionalscope: object = ...

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

    Returns EventHandle

    Can be used for removing event in the future.

    obj.on('test', function (a, b) {
    console.log(a + b);
    });
    obj.fire('test', 1, 2); // prints 3 to the console
    const evt = obj.on('test', function (a, b) {
    console.log(a + b);
    });
    // some time later
    evt.off();
  • Attach an event handler to an event. This handler will be removed after being fired once.

    Parameters

    • name: string

      Name of the event to bind the callback to.

    • callback: HandleEventCallback

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

    • Optionalscope: object = ...

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

    Returns EventHandle

    • can be used for removing event in the future.
    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
  • Resize the application's canvas element in line with the current fill mode.

    • In FILLMODE_KEEP_ASPECT mode, the canvas will grow to fill the window as best it can while maintaining the aspect ratio.
    • In FILLMODE_FILL_WINDOW mode, the canvas will simply fill the window, changing aspect ratio.
    • In FILLMODE_NONE mode, the canvas will always match the size provided.

    Parameters

    • Optionalwidth: number

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

    • Optionalheight: number

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

    Returns object

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

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

    Parameters

    • mode: string

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

      • RESOLUTION_AUTO: if width and height are not provided, canvas will be resized to match canvas client size.
      • RESOLUTION_FIXED: resolution of canvas will be fixed.
    • Optionalwidth: number

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

    • Optionalheight: number

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

    Returns void

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

    Returns void

    app.start();
    
  • 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

    • dt: number

      The time delta in seconds since the last frame.

    Returns void

  • 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 Application is not readily available. For example, in the JavaScript console of the browser's developer tools.

    Parameters

    • Optionalid: string

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

    Returns AppBase

    The running application, if any.

    const app = pc.AppBase.getApplication();