API Reference

Class List

CameraComponent

Extends: Component

The Camera Component enables an Entity to render the scene. A scene requires at least one enabled camera component to be rendered. Note that multiple camera components can be enabled simultaneously (for split-screen or offscreen rendering, for example).

// Add a pc.CameraComponent to an entity
const entity = new pc.Entity();
entity.addComponent('camera', {
    nearClip: 1,
    farClip: 100,
    fov: 55
});

// Get the pc.CameraComponent on an entity
const cameraComponent = entity.camera;

// Update a property on a camera component
entity.camera.nearClip = 2;

Summary

Properties

aperture

Set camera aperture in f-stops, the default value is 16.

aspectRatio

The aspect ratio (width divided by height) of the camera.

aspectRatioMode

The aspect ratio mode of the camera.

calculateProjection

Custom function you can provide to calculate the camera projection matrix manually.

calculateTransform

Custom function you can provide to calculate the camera transformation matrix manually.

clearColor

The color used to clear the canvas to before the camera starts to render.

clearColorBuffer

If true the camera will clear the color buffer to the color set in clearColor.

clearDepthBuffer

If true the camera will clear the depth buffer.

clearStencilBuffer

If true the camera will clear the stencil buffer.

cullFaces

If true the camera will take material.

disablePostEffectsLayer

Layer ID of a layer on which the postprocessing of the camera stops being applied to.

farClip

The distance from the camera after which no rendering will take place.

flipFaces

If true the camera will invert front and back faces.

fov

The field of view of the camera in degrees.

frustum

Queries the camera's frustum shape.

frustumCulling

Controls the culling of mesh instances against the camera frustum, i.

horizontalFov

Set which axis to use for the Field of View calculation.

layers

An array of layer IDs (Layer#id) to which this camera should belong.

nearClip

The distance from the camera before which no rendering will take place.

onPostRender

Custom function that is called after the camera renders the scene.

onPreRender

Custom function that is called before the camera renders the scene.

orthoHeight

The half-height of the orthographic view window (in the Y-axis).

postEffectsEnabled

The post effects queue for this camera.

priority

Controls the order in which cameras are rendered.

projection

The type of projection used to render the camera.

projectionMatrix

Queries the camera's projection matrix.

rect

Controls where on the screen the camera will be rendered in normalized screen coordinates.

renderTarget

Render target to which rendering of the cameras is performed.

scissorRect

Clips all pixels which are not in the rectangle.

sensitivity

Set camera sensitivity in ISO, the default value is 1000.

shutter

Set camera shutter speed in seconds, the default value is 1/1000s.

viewMatrix

Queries the camera's view matrix.

Methods

calculateAspectRatio

Calculates aspect ratio value for a given render target.

endXr

Attempt to end XR session of this camera.

getShaderPass

Shader pass name.

requestSceneColorMap

Request the scene to generate a texture containing the scene color map.

requestSceneDepthMap

Request the scene to generate a texture containing the scene depth map.

screenToWorld

Convert a point from 2D screen space to 3D world space.

setShaderPass

Sets the name of the shader pass the camera will use when rendering.

startXr

Attempt to start XR session with this camera.

worldToScreen

Convert a point from 3D world space to 2D screen space.

Inherited

Properties

enabled

Enables or disables the component.

entity

The Entity that this Component is attached to.

system

The ComponentSystem used to create this Component.

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

Constructor

CameraComponent(system, entity)

Create a new CameraComponent instance.

Parameters

systemCameraComponentSystem

The ComponentSystem that created this Component.

entityEntity

The Entity that this Component is attached to.

Properties

numberaperture

Set camera aperture in f-stops, the default value is 16.0. Higher value means less exposure.

numberaspectRatio

The aspect ratio (width divided by height) of the camera. If aspectRatioMode is ASPECT_AUTO, then this value will be automatically calculated every frame, and you can only read it. If it's ASPECT_MANUAL, you can set the value.

numberaspectRatioMode

The aspect ratio mode of the camera. Can be:

  • ASPECT_AUTO: aspect ratio will be calculated from the current render target's width divided by height.
  • ASPECT_MANUAL: use the aspectRatio value.

Defaults to ASPECT_AUTO.

CalculateMatrixCallbackcalculateProjection

Custom function you can provide to calculate the camera projection matrix manually. Can be used for complex effects like doing oblique projection. Function is called using component's scope. Arguments:

Left and right are only used in stereo rendering.

CalculateMatrixCallbackcalculateTransform

Custom function you can provide to calculate the camera transformation matrix manually. Can be used for complex effects like reflections. Function is called using component's scope. Arguments:

Left and right are only used in stereo rendering.

ColorclearColor

The color used to clear the canvas to before the camera starts to render. Defaults to [0.75, 0.75, 0.75, 1].

booleanclearColorBuffer

If true the camera will clear the color buffer to the color set in clearColor. Defaults to true.

booleanclearDepthBuffer

If true the camera will clear the depth buffer. Defaults to true.

booleanclearStencilBuffer

If true the camera will clear the stencil buffer. Defaults to true.

booleancullFaces

If true the camera will take material.cull into account. Otherwise both front and back faces will be rendered. Defaults to true.

numberdisablePostEffectsLayer

Layer ID of a layer on which the postprocessing of the camera stops being applied to. Defaults to LAYERID_UI, which causes post processing to not be applied to UI layer and any following layers for the camera. Set to undefined for post-processing to be applied to all layers of the camera.

numberfarClip

The distance from the camera after which no rendering will take place. Defaults to 1000.

booleanflipFaces

If true the camera will invert front and back faces. Can be useful for reflection rendering. Defaults to false.

numberfov

The field of view of the camera in degrees. Usually this is the Y-axis field of view, see CameraComponent#horizontalFov. Used for PROJECTION_PERSPECTIVE cameras only. Defaults to 45.

Frustumfrustum

Queries the camera's frustum shape.

booleanfrustumCulling

Controls the culling of mesh instances against the camera frustum, i.e. if objects outside of camera should be omitted from rendering. If false, all mesh instances in the scene are rendered by the camera, regardless of visibility. Defaults to false.

booleanhorizontalFov

Set which axis to use for the Field of View calculation. Defaults to false.

number[]layers

An array of layer IDs (Layer#id) to which this camera should belong. Don't push, pop, splice or modify this array, if you want to change it, set a new one instead. Defaults to [LAYERID_WORLD, LAYERID_DEPTH, LAYERID_SKYBOX, LAYERID_UI, LAYERID_IMMEDIATE].

numbernearClip

The distance from the camera before which no rendering will take place. Defaults to 0.1.

functiononPostRender

Custom function that is called after the camera renders the scene.

functiononPreRender

Custom function that is called before the camera renders the scene.

numberorthoHeight

The half-height of the orthographic view window (in the Y-axis). Used for PROJECTION_ORTHOGRAPHIC cameras only. Defaults to 10.

PostEffectQueuepostEffectsEnabled

The post effects queue for this camera. Use this to add or remove post effects from the camera.

numberpriority

Controls the order in which cameras are rendered. Cameras with smaller values for priority are rendered first. Defaults to 0.

numberprojection

The type of projection used to render the camera. Can be:

Defaults to PROJECTION_PERSPECTIVE.

Mat4projectionMatrix

Queries the camera's projection matrix.

Vec4rect

Controls where on the screen the camera will be rendered in normalized screen coordinates. Defaults to [0, 0, 1, 1].

RenderTargetrenderTarget

Render target to which rendering of the cameras is performed. If not set, it will render simply to the screen.

Vec4scissorRect

Clips all pixels which are not in the rectangle. The order of the values is [x, y, width, height]. Defaults to [0, 0, 1, 1].

numbersensitivity

Set camera sensitivity in ISO, the default value is 1000. Higher value means more exposure.

numbershutter

Set camera shutter speed in seconds, the default value is 1/1000s. Longer shutter means more exposure.

Mat4viewMatrix

Queries the camera's view matrix.

Methods

calculateAspectRatio([rt])

Calculates aspect ratio value for a given render target.

Parameters

rtRenderTarget

Optional render target. If unspecified, the backbuffer is used.

Returns

number

The aspect ratio of the render target (or backbuffer).

endXr([callback])

Attempt to end XR session of this camera.

// On an entity with a camera component
this.entity.camera.endXr(function (err) {
    // not anymore in XR
});

Parameters

callbackXrErrorCallback

Optional callback function called once session is ended. The callback has one argument Error - it is null if successfully ended XR session.

getShaderPass()

Shader pass name.

Returns

string

The name of the shader pass, or undefined if no shader pass is set.

requestSceneColorMap(enabled)

Request the scene to generate a texture containing the scene color map. Note that this call is accumulative, and for each enable request, a disable request need to be called.

Parameters

enabledboolean

True to request the generation, false to disable it.

requestSceneDepthMap(enabled)

Request the scene to generate a texture containing the scene depth map. Note that this call is accumulative, and for each enable request, a disable request need to be called.

Parameters

enabledboolean

True to request the generation, false to disable it.

screenToWorld(screenx, screeny, cameraz, [worldCoord])

Convert a point from 2D screen space to 3D world space.

// Get the start and end points of a 3D ray fired from a screen click position
const start = entity.camera.screenToWorld(clickX, clickY, entity.camera.nearClip);
const end = entity.camera.screenToWorld(clickX, clickY, entity.camera.farClip);

// Use the ray coordinates to perform a raycast
app.systems.rigidbody.raycastFirst(start, end, function (result) {
    console.log("Entity " + result.entity.name + " was selected");
});

Parameters

screenxnumber

X coordinate on PlayCanvas' canvas element. Should be in the range 0 to canvas.offsetWidth of the application's canvas element.

screenynumber

Y coordinate on PlayCanvas' canvas element. Should be in the range 0 to canvas.offsetHeight of the application's canvas element.

cameraznumber

The distance from the camera in world space to create the new point.

worldCoordVec3

3D vector to receive world coordinate result.

Returns

Vec3

The world space coordinate.

setShaderPass(name)

Sets the name of the shader pass the camera will use when rendering.

In addition to existing names (see the parameter description), a new name can be specified, which creates a new shader pass with the given name. The name provided can only use alphanumeric characters and underscores. When a shader is compiled for the new pass, a define is added to the shader. For example, if the name is 'custom_rendering', the define 'CUSTOM_RENDERING_PASS' is added to the shader, allowing the shader code to conditionally execute code only when that shader pass is active.

Another instance where this approach may prove useful is when a camera needs to render a more cost-effective version of shaders, such as when creating a reflection texture. To accomplish this, a callback on the material that triggers during shader compilation can be used. This callback can modify the shader generation options specifically for this shader pass.

const shaderPassId = camera.setShaderPass('custom_rendering');

material.onUpdateShader = function (options) {
    if (options.pass === shaderPassId) {
        options.litOptions.normalMapEnabled = false;
        options.litOptions.useSpecular = false;
    }
    return options;
};

Parameters

namestring

The name of the shader pass. Defaults to undefined, which is equivalent to SHADERPASS_FORWARD. Can be:

Returns

number

The id of the shader pass.

startXr(type, spaceType, [options])

Attempt to start XR session with this camera.

// On an entity with a camera component
this.entity.camera.startXr(pc.XRTYPE_VR, pc.XRSPACE_LOCAL, {
    callback: function (err) {
        if (err) {
            // failed to start XR session
        } else {
            // in XR
        }
    }
});

Parameters

typestring

The type of session. Can be one of the following:

  • XRTYPE_INLINE: Inline - always available type of session. It has limited feature availability and is rendered into HTML element.
  • XRTYPE_VR: Immersive VR - session that provides exclusive access to the VR device with the best available tracking features.
  • XRTYPE_AR: Immersive AR - session that provides exclusive access to the VR/AR device that is intended to be blended with the real-world environment.
spaceTypestring

Reference space type. Can be one of the following:

  • XRSPACE_VIEWER: Viewer - always supported space with some basic tracking capabilities.
  • XRSPACE_LOCAL: Local - represents a tracking space with a native origin near the viewer at the time of creation. It is meant for seated or basic local XR sessions.
  • XRSPACE_LOCALFLOOR: Local Floor - represents a tracking space with a native origin at the floor in a safe position for the user to stand. The y-axis equals 0 at floor level. Floor level value might be estimated by the underlying platform. It is meant for seated or basic local XR sessions.
  • XRSPACE_BOUNDEDFLOOR: Bounded Floor - represents a tracking space with its native origin at the floor, where the user is expected to move within a pre-established boundary.
  • XRSPACE_UNBOUNDED: Unbounded - represents a tracking space where the user is expected to move freely around their environment, potentially long distances from their starting point.
optionsobject

Object with options for XR session initialization.

options.optionalFeaturesstring[]

Optional features for XRSession start. It is used for getting access to additional WebXR spec extensions.

options.imageTrackingboolean

Set to true to attempt to enable XrImageTracking.

options.planeDetectionboolean

Set to true to attempt to enable XrPlaneDetection.

options.callbackXrErrorCallback

Optional callback function called once the session is started. The callback has one argument Error - it is null if the XR session started successfully.

options.depthSensingobject

Optional object with depth sensing parameters to attempt to enable XrDepthSensing.

options.depthSensing.usagePreferencestring

Optional usage preference for depth sensing, can be 'cpu-optimized' or 'gpu-optimized' (XRDEPTHSENSINGUSAGE_*), defaults to 'cpu-optimized'. Most preferred and supported will be chosen by the underlying depth sensing system.

options.depthSensing.dataFormatPreferencestring

Optional data format preference for depth sensing. Can be 'luminance-alpha' or 'float32' (XRDEPTHSENSINGFORMAT_*), defaults to 'luminance-alpha'. Most preferred and supported will be chosen by the underlying depth sensing system.

worldToScreen(worldCoord, [screenCoord])

Convert a point from 3D world space to 2D screen space.

Parameters

worldCoordVec3

The world space coordinate.

screenCoordVec3

3D vector to receive screen coordinate result.

Returns

Vec3

The screen space coordinate.

Inherited

Properties

booleanenabled

Enables or disables the component.

Entityentity

The Entity that this Component is attached to.

ComponentSystemsystem

The ComponentSystem used to create this Component.

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

namestring

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

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.

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

Parameters

namestring

Name of the event to unbind.

callbackHandleEventCallback

Function to be unbound.

scopeobject

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

Returns

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.

callbackHandleEventCallback

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

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.

callbackHandleEventCallback

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

EventHandler

Self for chaining.