# PlayCanvas Developer Documentation - Full Content > The complete text of the PlayCanvas User Manual in one file, for indexing, or for downloading and searching. Index: https://developer.playcanvas.com/llms.txt Total Documents: 563 Generated: 2026-11-19 ================================================================================ ## Welcome URL: https://developer.playcanvas.com/user-manual/ Markdown: https://developer.playcanvas.com/user-manual.md Welcome to the PlayCanvas User Manual. Your exciting journey learning PlayCanvas begins now! [Image: PlayCanvas Demos] Let's [get started](https://developer.playcanvas.com/user-manual/getting-started.md)! -------------------------------------------------------------------------------- ## Getting Started URL: https://developer.playcanvas.com/user-manual/getting-started/ Markdown: https://developer.playcanvas.com/user-manual/getting-started.md ## What is PlayCanvas? PlayCanvas is a โœจ **web graphics creation platform** โœจ PlayCanvas is a collection of open-source products that you can use to build interactive, graphical web applications: ๐Ÿฆพ [**PlayCanvas Engine**](https://developer.playcanvas.com/user-manual/engine.md) - Open source JavaScript run-time that powers all PlayCanvas applications ๐Ÿ› ๏ธ [**PlayCanvas Editor**](https://developer.playcanvas.com/user-manual/editor.md) - Real-time collaborative visual editing environment for building PlayCanvas applications โš›๏ธ [**PlayCanvas React**](https://developer.playcanvas.com/user-manual/react.md) - Open source React-based declarative interface that wraps the PlayCanvas Engine ๐Ÿงฉ [**PlayCanvas Web Components**](https://developer.playcanvas.com/user-manual/web-components.md) - Open source Web Components-based declarative interface that wraps the PlayCanvas Engine ## Start a Code Project Use [`create-playcanvas`](https://developer.playcanvas.com/user-manual/getting-started/start-with-create-playcanvas.md) to scaffold a Vite and TypeScript project for the Engine, React, or Web Components from one of its runnable starters. New projects include [PlayCanvas Skills](https://developer.playcanvas.com/user-manual/getting-started/use-playcanvas-skills.md), which give compatible AI coding agents PlayCanvas-specific development and verification workflows. ## Coming from Unity [Migrating from Unity](https://developer.playcanvas.com/user-manual/getting-started/migrating-from-unity.md) maps the Unity Editor, Unity's concepts and its C# APIs to their PlayCanvas equivalents, and explains the differences that catch Unity developers out. ## Which Product is Right For You? Every developer is different, so picking the right entry point to PlayCanvas will depend on your background and skills. Let us help you choose: ### ๐Ÿฆพ [**PlayCanvas Engine**](https://developer.playcanvas.com/user-manual/engine.md) - *Full control development* **Best for:** Experienced programmers, performance-critical applications, custom workflows **Choose if you:** Want maximum control, have specific architectural needs, or are building complex systems ### ๐Ÿ› ๏ธ [**PlayCanvas Editor**](https://developer.playcanvas.com/user-manual/editor.md) - *Visual-first development* **Best for:** Beginners, teams, rapid prototyping, visual learners **Choose if you:** Want drag-and-drop scene building, real-time collaboration, or prefer visual tools over code ### โš›๏ธ [**PlayCanvas React**](https://developer.playcanvas.com/user-manual/react.md) - *React developers* **Best for:** React developers, component-based thinkers, existing React projects **Choose if you:** Already use React, want declarative 3D scenes, or need to integrate 3D into React apps ### ๐Ÿงฉ [**PlayCanvas Web Components**](https://developer.playcanvas.com/user-manual/web-components.md) - *Standards-based development* **Best for:** Vanilla JS developers, framework-agnostic projects, web standards enthusiasts **Choose if you:** Prefer native web technologies, want framework independence, or like custom HTML elements ### ๐Ÿ˜• Still Confused? Consult this simple questionnaire: **New to 3D development?** โ†’ Start with the [**PlayCanvas Editor**](https://developer.playcanvas.com/user-manual/editor.md) **React developer?** โ†’ Use [**PlayCanvas React**](https://developer.playcanvas.com/user-manual/react.md) **Prefer vanilla HTML and JavaScript?** โ†’ Try [**PlayCanvas Web Components**](https://developer.playcanvas.com/user-manual/web-components.md) **A coder that needs maximum control?** โ†’ Go with the [**PlayCanvas Engine**](https://developer.playcanvas.com/user-manual/engine.md) **Working in a team?** โ†’ The [**PlayCanvas Editor**](https://developer.playcanvas.com/user-manual/editor.md) offers the best collaboration **Coming from Unity or Unreal?** โ†’ The [**PlayCanvas Editor**](https://developer.playcanvas.com/user-manual/editor.md) provides a similar end-user experience. Unity developers, see [Migrating from Unity](https://developer.playcanvas.com/user-manual/getting-started/migrating-from-unity.md) **Integrating into existing app or site?** โ†’ Choose [**React**](https://developer.playcanvas.com/user-manual/react.md) or [**Web Components**](https://developer.playcanvas.com/user-manual/web-components.md) based on your existing stack And if you still have questions, come and chat to us on [Discord](https://discord.gg/RSaMRzg). -------------------------------------------------------------------------------- ## Start with create-playcanvas URL: https://developer.playcanvas.com/user-manual/getting-started/start-with-create-playcanvas/ Markdown: https://developer.playcanvas.com/user-manual/getting-started/start-with-create-playcanvas.md [`create-playcanvas`](https://github.com/playcanvas/create-playcanvas) is the official scaffolding tool for code-based PlayCanvas projects. It creates a Vite and TypeScript project for the PlayCanvas Engine, React, or Web Components and includes a runnable starter scene. ## Create a Project Run the creator with your preferred package manager: ```sh # npm npm create playcanvas@latest # pnpm pnpm create playcanvas@latest # Yarn yarn create playcanvas # Bun bun x create-playcanvas@latest ``` Follow the prompts to name the project, choose an authoring format, and select a starter. The creator requires Node.js 22.23.2 or later when using npm, pnpm, or Yarn. After the files are created, install the dependencies and start the Vite development server: ```sh cd my-playcanvas-project npm install npm run dev ``` When you are ready to deploy, run `npm run build` to create a production build. Its URLs are relative, so it works from any folder on a server, not only from the root of a domain. ## Choose a Format Every format uses TypeScript and includes Vite, ESLint, Prettier, and a production build. | Format | Use it when | | --- | --- | | Engine | You want to work directly with the `playcanvas` API. | | React | You are building a React application with `@playcanvas/react`. | | Web Components | You want declarative custom elements from `@playcanvas/web-components`. | ## Choose a Starter The creator provides the same runnable starters for every format: [Image: The create-playcanvas starter scenes] | Category | Starters | | --- | --- | | Basics | Spinning Cube, Interactive Sphere | | Viewers | Model Viewer, Splat Viewer, Product Configurator | | Games | Physics Playground, First-Person Controller, Third-Person Controller, Sprite Game, Snapchat Web Lens | | Tools | Scene Editor | | XR | VR Starter, AR Placement | Choose the starter closest to the application you want to build, run it unchanged first, and then replace its assets and behavior incrementally. ## Snapchat Web Lens Starter The Snapchat Web Lens starter is a portrait game set up to run inside Snapchat as a [Web Lens](https://developers.snap.com/web-lenses/home): ```sh npm create playcanvas@latest my-lens -- --starter web-lens ``` It is set up for Snap's [platform requirements](https://developers.snap.com/web-lenses/requirements): a portrait layout that keeps the heads-up display (HUD) clear of Snapchat's controls, relative URLs in the build, and no requests to other hosts. Through the [Web Lens API](https://developers.snap.com/web-lenses/web-lens-api), it submits each run to the leaderboard, keeps the player's best score in Snapchat storage, and shows their Bitmoji. Outside Snapchat, the API answers from a built-in stub, so the game runs in any browser. To make it your own, replace the game in `src/dodge-game.ts` and keep the rest. The project's README lists which files to replace and which to keep. When your game is ready, package it: ```sh npm run package ``` This builds the game, checks the build against Snap's upload rules, and writes a zip to `dist/`. If a check fails, it names the file to fix and writes no zip. Upload the zip through [My Lenses](https://my-lenses.snapchat.com/), following Snap's [Publishing](https://developers.snap.com/web-lenses/publishing) guide. To publish an Editor project as a Web Lens instead, see [Snapchat Web Lenses](https://developer.playcanvas.com/user-manual/editor/publishing/snapchat-web-lenses.md). ## Debug with the Inspector The development server loads the [Inspector](https://developer.playcanvas.com/user-manual/debugging/inspector.md) for the running application. Press the backquote key (`` ` ``) to show or hide it, F9 to pause, and F10 to step one frame. Production builds do not include the Inspector. ## Skip the Prompts Pass a project name, format, and starter to create a project non-interactively: ```sh npm create playcanvas@latest my-viewer -- -f react -s model-viewer ``` When there is no terminal to answer the prompts, as when an AI coding agent or an automated build runs the command, the creator takes the defaults for any option you do not pass, as `--yes` does. It still stops with an error when a choice has no safe default, such as a non-empty target directory without `--keep` or `--overwrite`. | Option | Shorthand | Purpose | | --- | --- | --- | | `--format ` | `-f` | Choose `engine`, `react`, or `web-components`. | | `--starter ` | `-s` | Choose one of the starters above. | | `--yes` | `-y` | Accept the default Engine and Spinning Cube choices. | | `--no-skills` | | Omit the PlayCanvas Skills included by default. | | `--keep` | | Add the project to a non-empty target directory without replacing its files. | | `--overwrite` | | Replace files in a non-empty target directory. | | `--help` | `-h` | Show the current command options. | :::warning `--overwrite` removes existing files from the target directory. Use a new directory unless you intend to replace its contents. ::: `--keep` adds the project to a directory that already holds files, such as a brief or assets, and replaces none of them. Where the project has a file of the same name, yours stays and the creator lists it. It stops with an error if the directory already has a `package.json`. ## Included PlayCanvas Skills New projects include [PlayCanvas Skills](https://developer.playcanvas.com/user-manual/getting-started/use-playcanvas-skills.md) under `.claude/skills/` and `.agents/skills/`. Compatible AI coding agents can use them to follow PlayCanvas-specific workflows for application setup, assets, scenes, animation, lighting, effects, rendering verification, performance, and runtime inspection. Pass `--no-skills` only when the project does not use an AI coding agent or you manage the skills through another installation route. ## Next Steps - For the direct Engine API, continue with [Using the Engine Standalone](https://developer.playcanvas.com/user-manual/engine/standalone.md). - For React, continue with [Building a Scene](https://developer.playcanvas.com/user-manual/react/building-a-scene.md). - For Web Components, continue with [Building a Scene](https://developer.playcanvas.com/user-manual/web-components/building-a-scene.md). -------------------------------------------------------------------------------- ## Use PlayCanvas Skills URL: https://developer.playcanvas.com/user-manual/getting-started/use-playcanvas-skills/ Markdown: https://developer.playcanvas.com/user-manual/getting-started/use-playcanvas-skills.md [PlayCanvas Skills](https://github.com/playcanvas/skills) are portable instructions, references, and utilities for AI coding agents. They help an agent inspect the real project and installed packages, use the matching PlayCanvas authoring surface, and verify the result in a running application. The skills support code-based applications built with the PlayCanvas Engine, React, and Web Components. They do not run in the application or add a runtime dependency. :::ai PlayCanvas is listed in the Anthropic Directory. In Claude Code, run `/plugin`, open **Discover**, and search for `playcanvas`. ::: ## Start a New Project The quickest way to start is with [`create-playcanvas`](https://developer.playcanvas.com/user-manual/getting-started/start-with-create-playcanvas.md): ```sh npm create playcanvas@latest ``` Every generated project includes the skills under `.claude/skills/` for Claude Code and `.agents/skills/` for Codex, Cursor, and other Agent Skills-compatible clients. Install the project dependencies, open the project root in your client, and start a new conversation so it discovers the skills. ## Add Skills to an Existing Project Use the [Agent Skills](https://skills.sh/) installer from the project root: ```sh npx skills add playcanvas/skills ``` Use `--all` to install every skill into all detected clients, or `-g` for a user-level installation. ## Install the Claude Code Plugin PlayCanvas is listed in the Anthropic Directory for Claude Code. In Claude Code or the Code tab in Claude Desktop, run `/plugin`, open **Discover**, and search for `playcanvas`. In the desktop app's Code tab, installed plugins are available under **+ > Plugins**. Use one installation route per client so the same skills are not exposed twice. For example, do not install both the Agent Skills package and the Claude Code plugin for Claude Code. The [PlayCanvas Skills repository](https://github.com/playcanvas/skills#native-plugins) also documents its marketplace installation for Claude Code, Codex, and Cursor. After installing or updating the skills, start a new agent conversation so the client reloads their metadata. ## What the Skills Cover The collection is organized around the work required to turn a project brief and source assets into a verified application: | Workflow | Skills | | --- | --- | | Application setup and conventions | `build-app`, `apply-conventions` | | Official examples and Engine features | `find-examples`, `reuse-scripts` | | Assets, models, and animation | `load-assets`, `inspect-glb`, `calibrate-model`, `configure-animation` | | Scene composition and runtime inspection | `assemble-scene`, `inspect-runtime` | | Lighting and effects | `light-scene`, `bake-lighting`, `add-effects`, `override-shader-chunks` | | Rendering verification and performance | `verify-pixels`, `reduce-draw-calls` | The agent loads only the skills relevant to the current task. Each skill tells it which installed package declarations, Engine source, scripts, or official examples to inspect before choosing an API or implementation. ## Ask for an Outcome Describe the result you want and the evidence required to accept it. You do not need to name every skill yourself. For example: ```text Build a Direct Engine product viewer for these GLBs. Inspect and calibrate every model, reuse the shipped camera controls, and verify grounding and framing in the browser. ``` ```text Polish this PlayCanvas React prototype with fewer draw calls, pooled effects, coherent lighting, and screenshot checks. ``` The agent should inspect the project before editing, preserve the active Engine, React, or Web Components surface, run the project's checks, and verify interactive or visual behavior in the browser. For broader guidance on project context, prompts, browser tools, and evidence, see [Developing with AI](https://developer.playcanvas.com/user-manual/engine/developing-with-ai.md). ## Scope PlayCanvas Skills target code-based Engine application workflows. They do not automate PlayCanvas Editor projects, publish applications, manage PlayCanvas services, or replace project-specific art direction and gameplay design. For AI-assisted Editor workflows, use the [Editor MCP Server](https://developer.playcanvas.com/user-manual/editor/mcp-server.md) and [VS Code Extension](https://developer.playcanvas.com/user-manual/editor/scripting/vscode-extension.md). To report a repeatable problem or suggest an improvement, use the [skill feedback form](https://github.com/playcanvas/skills/issues/new?template=skill-feedback.yml). -------------------------------------------------------------------------------- ## Migrating from Unity URL: https://developer.playcanvas.com/user-manual/getting-started/migrating-from-unity/ Markdown: https://developer.playcanvas.com/user-manual/getting-started/migrating-from-unity.md If you have built projects in Unity, much of PlayCanvas will feel familiar. The [PlayCanvas Editor](https://developer.playcanvas.com/user-manual/editor.md) has a hierarchy, an inspector, an assets panel and a 3D viewport. Scenes are trees of entities, entities are made of components, and behavior is written in scripts with lifecycle methods such as `initialize` and `update`. This guide maps what you know from Unity to PlayCanvas: the Editor's panels and shortcuts, the names of common concepts, C# APIs and their JavaScript equivalents, and the places where PlayCanvas works differently. Each section links to the full documentation for its topic. ## Key Differences - **Everything runs in the browser.** The Editor is a web application, your project is stored online, and what you publish is a web app. There is no WebGL build to wait for: your app runs on the same engine as the Editor's viewport. - **Scripts are JavaScript.** You write scripts as JavaScript modules instead of C# classes, and nothing is compiled: save a script and launch. - **Scripts share one component.** In Unity, each MonoBehaviour is a component of its own. In PlayCanvas, an entity has one Script component, which holds all of its scripts. - **One component of each type per entity.** An entity can have one camera, one light, one collision component and so on, and each script once. When you need two of something, such as two colliders, use child entities. - **The coordinate system is right-handed.** Forward is -Z rather than +Z. See [Coordinate System and Units](https://developer.playcanvas.com/user-manual/getting-started/migrating-from-unity.md#coordinate-system-and-units). - **There is no Play Mode.** Launch runs your scene in a separate browser tab that stays connected to the Editor. - **Collaboration and version control are built in.** Several people can edit the same scene at the same time, and checkpoints, branches and merging are part of the Editor. ## The Editor The Editor's layout is much like Unity's default layout: [Image: The PlayCanvas Editor, with the toolbar, hierarchy, viewport, inspector and assets panel numbered 1 to 5] | | PlayCanvas | Unity | | --- | --- | --- | | 1 | [Toolbar](https://developer.playcanvas.com/user-manual/editor/interface/toolbar.md) | The main menu, the transform tools and the toolbar | | 2 | [Hierarchy](https://developer.playcanvas.com/user-manual/editor/interface/hierarchy.md) | Hierarchy window | | 3 | [Viewport](https://developer.playcanvas.com/user-manual/editor/interface/viewport.md) | Scene view | | 4 | [Inspector](https://developer.playcanvas.com/user-manual/editor/interface/inspector.md) | Inspector window | | 5 | [Assets panel](https://developer.playcanvas.com/user-manual/editor/interface/assets.md) | Project window | Other Unity windows and menus have these equivalents: | Unity | PlayCanvas | | --- | --- | | Play button and Game view | The [Launch](https://developer.playcanvas.com/user-manual/editor/interface/launch-page.md) button at the top right of the viewport | | Console window | The browser's developer tools console in the launched tab. The Editor's own **CONSOLE** panel, at the bottom left, shows Editor messages such as script parse errors. | | Project Settings and Lighting window | [Settings](https://developer.playcanvas.com/user-manual/editor/interface/settings.md), from the cog icon on the toolbar | | Build Settings | **Publish / Download** on the toolbar | | Animator window | The [anim state graph](https://developer.playcanvas.com/user-manual/animation/state-graphs.md) editor, which opens when you select an anim state graph asset | | Asset Store | **ASSET STORE** at the top right of the assets panel, with PlayCanvas Store and Sketchfab assets | | Visual Studio or Rider | The built-in [Code Editor](https://developer.playcanvas.com/user-manual/editor/scripting/code-editor.md), or VS Code with the [VS Code extension](https://developer.playcanvas.com/user-manual/editor/scripting/vscode-extension.md) | | Unity Version Control or Git | Built-in [version control](https://developer.playcanvas.com/user-manual/editor/version-control.md) | ### Launching Instead of Play Mode Unity plays your game inside the Editor. PlayCanvas opens it in a new browser tab, the [Launch Page](https://developer.playcanvas.com/user-manual/editor/interface/launch-page.md), which runs your scene just as it will run when published. Click **Launch**, or press Ctrl+Enter. The Launch Page stays connected to the Editor. Changes to entities, components, script attributes, assets and scene settings show up in the running app as you make them, and unlike edits made in Play Mode, they are not thrown away when you stop: the Editor saves every change as you make it. Place the two tabs side by side to work this way. Code changes need a reload, unless the script supports [hot reloading](https://developer.playcanvas.com/user-manual/editor/scripting/hot-reloading.md). Scripts never run in the Editor's viewport, so there is nothing like Unity's `[ExecuteInEditMode]`: anything a script creates or changes appears only in the launched app. The Launch button's menu has options for testing: choose the graphics API, open the [Profiler](https://developer.playcanvas.com/user-manual/optimization/profiler.md), [MiniStats](https://developer.playcanvas.com/user-manual/optimization/mini-stats.md) or [Inspector](https://developer.playcanvas.com/user-manual/debugging/inspector.md), and tick **Debug** to log the engine's warnings and errors to the console. ### Navigating the Viewport | Action | Unity | PlayCanvas | | --- | --- | --- | | Orbit | Alt + left-drag | Left-drag | | Look around | Right-drag | Right-drag | | Pan | Middle-drag | Middle-drag, or Shift + left-drag | | Zoom | Mouse wheel | Mouse wheel | | Fly | Hold the right mouse button and press W, A, S, D, Q, E | Press W, A, S, D, Q, E, with no mouse button held (hold Shift to go faster) | | Frame the selection | F | F | | Rectangle selection | Left-drag over empty space | Ctrl + left-drag | | Add to or remove from the selection | Shift+click or Ctrl+click | Ctrl+click | ### Keyboard Shortcuts | Action | Unity | PlayCanvas | | --- | --- | --- | | Move tool | W | 1 | | Rotate tool | E | 2 | | Scale tool | R | 3 | | Rect tool (UI elements) | T | 4 | | Toggle local and world gizmo space | X | L | | Frame the selection | F | F | | Play | Ctrl+P | Ctrl+Enter (Launch) | | Create an empty child | Alt+Shift+N | Ctrl+E | | Duplicate | Ctrl+D | Ctrl+D | | Rename | F2 | F2 | | Delete | Delete | Delete | | Undo / redo | Ctrl+Z / Ctrl+Y | Ctrl+Z / Ctrl+Y | | Save | Ctrl+S | Not needed, because every change is saved. Ctrl+S opens the form for creating a version control checkpoint. | | Maximize the view | Shift+Space | Space (hides the Hierarchy, Inspector and Assets panels) | | Front, right and top views | Click the arms of the Scene Gizmo | Numpad 1, 3 and 7 (add Ctrl for the opposite side), or click the axes of the view cube | | Toggle orthographic and perspective | Click the center of the Scene Gizmo | Numpad 5 | On macOS, use Cmd in place of Ctrl. Unity's View tool (Q) has no equivalent, because navigating the viewport never needs a tool. The full list is on the [Controls & Keyboard Shortcuts](https://developer.playcanvas.com/user-manual/editor/interface/keyboard-shortcuts.md) page. ## Concepts and Terminology | Unity | PlayCanvas | Notes | | --- | --- | --- | | GameObject | [Entity](https://developer.playcanvas.com/user-manual/ecs/entities.md) | | | Component | [Component](https://developer.playcanvas.com/user-manual/ecs/components.md) | Components are properties of the entity: `entity.camera`, `entity.light`. | | Transform | Part of every entity | Entities have a position, rotation and scale of their own. See [Hierarchy and Transforms](https://developer.playcanvas.com/user-manual/ecs/hierarchy-and-transformations.md). | | MonoBehaviour | [Script](https://developer.playcanvas.com/user-manual/scripting.md) | Attached through an entity's Script component. | | Prefab | [Template](https://developer.playcanvas.com/user-manual/editor/templates.md) | See [Prefabs and Templates](https://developer.playcanvas.com/user-manual/getting-started/migrating-from-unity.md#prefabs-and-templates). | | Scene | [Scene](https://developer.playcanvas.com/user-manual/editor/scenes.md) | | | Tag | [Tags](https://developer.playcanvas.com/user-manual/ecs/searching-the-hierarchy.md#by-tag) | An entity can have any number of tags. | | Layer | [Layers](https://developer.playcanvas.com/user-manual/graphics/layers.md) | Rendering only. Physics uses collision groups and masks. | | Mesh Filter and Mesh Renderer | [Render](https://developer.playcanvas.com/user-manual/editor/scenes/components/render.md) component | Skinned meshes use the Render component too. | | Material | [Material](https://developer.playcanvas.com/user-manual/editor/assets/inspectors/material.md) | | | Camera | [Camera](https://developer.playcanvas.com/user-manual/editor/scenes/components/camera.md) component | | | Light | [Light](https://developer.playcanvas.com/user-manual/editor/scenes/components/light.md) component | A point light is called an omni light. | | Rigidbody | [Rigid Body](https://developer.playcanvas.com/user-manual/editor/scenes/components/rigidbody.md) component | | | Collider | [Collision](https://developer.playcanvas.com/user-manual/editor/scenes/components/collision.md) component | Without a rigid body, a collision component is a trigger. See [Physics](https://developer.playcanvas.com/user-manual/getting-started/migrating-from-unity.md#physics). | | Audio Source | [Sound](https://developer.playcanvas.com/user-manual/editor/scenes/components/sound.md) component | One component plays any number of sounds, called slots. | | Audio Listener | [Audio Listener](https://developer.playcanvas.com/user-manual/editor/scenes/components/audiolistener.md) component | | | Particle System | [Particle System](https://developer.playcanvas.com/user-manual/editor/scenes/components/particlesystem.md) component | | | Animator and Animator Controller | [Anim](https://developer.playcanvas.com/user-manual/editor/scenes/components/anim.md) component and [anim state graph](https://developer.playcanvas.com/user-manual/animation/state-graphs.md) asset | | | Canvas | [Screen](https://developer.playcanvas.com/user-manual/editor/scenes/components/screen.md) component | | | RectTransform, Image and Text | [Element](https://developer.playcanvas.com/user-manual/editor/scenes/components/element.md) component | | | Sprite Renderer | [Sprite](https://developer.playcanvas.com/user-manual/editor/scenes/components/sprite.md) component | | | ScriptableObject | [JSON](https://developer.playcanvas.com/user-manual/editor/assets/inspectors/json.md) asset | Or a JavaScript module that exports the data. | | `Resources` and Addressables | The [asset registry](https://developer.playcanvas.com/user-manual/assets/asset-registry.md) | See [Assets](https://developer.playcanvas.com/user-manual/getting-started/migrating-from-unity.md#assets). | ## Coordinate System and Units Both engines use Y as up, measure distances in meters and take angles in degrees. The difference is handedness: Unity's coordinate system is left-handed with +Z forward, while PlayCanvas's is right-handed with **-Z forward**. Cameras look down their negative Z axis, `entity.forward` returns the negative Z axis, and `lookAt` points the negative Z axis at its target. [Image: Unity's left-handed axes with +Z forward beside PlayCanvas's right-handed axes with -Z forward] This has a few consequences when you port code and content: - **Moving forward means moving along -Z.** `transform.Translate(0, 0, speed * Time.deltaTime)` becomes `this.entity.translateLocal(0, 0, -this.speed * dt)`. - **Positive rotations turn the other way.** A positive rotation about Y turns an entity to its left (counter-clockwise seen from above), and a positive rotation about X tilts it up. In Unity they turn right and down, so a camera that looks down at the scene has a negative X rotation in PlayCanvas. - **Euler angles are applied in a different order.** PlayCanvas applies the X rotation first, then Y, then Z, while Unity applies Z, then X, then Y. Together with the flipped axis, this means rotations you read off Unity's Inspector don't carry over. Bring layouts across in exported files instead, which convert them. See [Bringing Your Content Over](https://developer.playcanvas.com/user-manual/getting-started/migrating-from-unity.md#bringing-your-content-over). - **Lights shine down -Y.** Directional and spot lights point along their local negative Y axis, so an unrotated light shines straight down. In Unity they shine along +Z. - **Models usually face +Z.** glTF defines +Z as the front of a model, and models exported from Unity keep facing +Z, which is backward in PlayCanvas. If a script moves a character along `entity.forward`, put the model inside a parent entity and rotate it 180ยฐ about Y, so that the model faces the parent's forward direction. - **The default field of view is narrower.** Both engines measure the field of view vertically, but a new PlayCanvas camera starts at 45ยฐ rather than 60ยฐ. ## Scripting PlayCanvas scripts are JavaScript classes that extend [`Script`](https://api.playcanvas.com/engine/classes/Script.html). Each lives in a `.mjs` file in the assets panel, and you attach it to an entity by adding a Script component and choosing the script. See [Scripting](https://developer.playcanvas.com/user-manual/scripting.md) for the complete guide. ### A Script Side by Side Here is a Unity script that spins its GameObject and switches a light on and off with the space bar: ```csharp using UnityEngine; public class Spinner : MonoBehaviour { // Degrees per second [SerializeField] float speed = 90f; [SerializeField] Light lamp; void Start() { lamp.enabled = false; } void Update() { transform.Rotate(0f, speed * Time.deltaTime, 0f); if (Input.GetKeyDown(KeyCode.Space)) { lamp.enabled = !lamp.enabled; Debug.Log($"Lamp on: {lamp.enabled}"); } } } ``` And here is the same script for PlayCanvas, in a file called `spinner.mjs`: ```javascript import { Entity, KEY_SPACE, Script } from 'playcanvas'; export class Spinner extends Script { static scriptName = 'spinner'; /** * Degrees per second. * * @attribute */ speed = 90; /** * @attribute * @type {Entity} */ lamp; initialize() { this.lamp.light.enabled = false; } update(dt) { this.entity.rotateLocal(0, this.speed * dt, 0); if (this.app.keyboard.wasPressed(KEY_SPACE)) { this.lamp.light.enabled = !this.lamp.light.enabled; console.log(`Lamp on: ${this.lamp.light.enabled}`); } } } ``` The differences to note: - **`scriptName` names the script.** The Editor lists the script under this name, and other scripts use it to reach the script: `entity.script.spinner`. - **`@attribute` takes the place of `[SerializeField]`.** Class fields tagged with `@attribute` in a JSDoc comment appear in the Inspector, and the comment's first sentence becomes the field's tooltip. See [Inspector Fields](https://developer.playcanvas.com/user-manual/getting-started/migrating-from-unity.md#inspector-fields). - **Entity attributes reference entities, not components.** An attribute of type `Entity` holds the entity, so you reach its components through it, as in `this.lamp.light`. - **`this.entity` is the GameObject and its transform.** `this.app` is the application, which gives you input devices, the scene hierarchy (`this.app.root`), the asset registry and more. - **`dt` is `Time.deltaTime`.** The engine passes the frame time, in seconds, to `update`. ### Lifecycle Methods | Unity | PlayCanvas | Notes | | --- | --- | --- | | `Awake`, `Start` | `initialize()` | Called once, the first time the script and its entity are both enabled. Don't use the class constructor for setup. | | `Start` that depends on another script's `Awake` | `postInitialize()` | Called after `initialize` has run on every script, so other scripts are ready. | | `Update` | `update(dt)` | | | `LateUpdate` | `postUpdate(dt)` | Called after `update` has run on every script. | | `FixedUpdate` | None | The physics engine steps at a fixed rate on its own. See [Physics](https://developer.playcanvas.com/user-manual/getting-started/migrating-from-unity.md#physics). | | `OnEnable`, `OnDisable` | `enable` and `disable` events | Subscribe with `this.on('enable', ...)`. | | `OnDestroy` | `destroy` event | Subscribe with `this.once('destroy', ...)`, and unsubscribe from other events there. | | `OnValidate` | An attribute setter | See [Responding to Attribute Changes](https://developer.playcanvas.com/user-manual/scripting/script-attributes/esm.md#responding-to-attribute-changes). | | `OnCollisionEnter`, `OnTriggerEnter` and so on | Collision component events | See [Physics](https://developer.playcanvas.com/user-manual/getting-started/migrating-from-unity.md#physics). | See [Script Lifecycle](https://developer.playcanvas.com/user-manual/scripting/script-lifecycle.md) for the details. ### Inspector Fields Script attributes are PlayCanvas's serialized fields. The Editor reads them from your code, so after you add or change one, click **Parse** on the script asset or the Script component to update the Inspector. | Unity | PlayCanvas | | --- | --- | | `[SerializeField] float speed = 5f;` | `/** @attribute */ speed = 5;` | | `[Tooltip("...")]` | The first sentence of the attribute's JSDoc comment | | `[Range(0, 10)]` | `@range [0, 10]` | | `[Min(0)]` | `@range [0]` | | `[HideInInspector]`, or no `[SerializeField]` | A field without `@attribute` | | `GameObject` or `Transform` field | `@type {Entity}` | | `Texture2D`, `Material`, `AudioClip` field | `@type {Asset}` with `@resource texture`, `material` or `audio` | | Prefab field | `@type {Asset}` with `@resource template` | | `Color`, `Vector3` field | `color = new Color()`, `offset = new Vec3()` | | `AnimationCurve` field | `@type {Curve}` | | Array or `List` field | An array type, such as `@type {Entity[]}` | | `enum` field | An `@enum` object, or a union of literals such as `@type {'low' \| 'high'}` | | `[Serializable]` class field | An `@interface` class or a `@typedef` | Attribute values set in the Editor are applied before `initialize` runs. See the [attributes reference](https://developer.playcanvas.com/user-manual/scripting/script-attributes/esm.md) for every tag. ### Common API Equivalents In these tables, `entity` stands for any entity, such as `this.entity` in a script, and imports such as `Vec3` and `KEY_W` come from `playcanvas`. #### Entities and Components | Unity | PlayCanvas | | --- | --- | | `new GameObject("Box")` | `const box = new Entity('Box'); this.app.root.addChild(box);` | | `Instantiate(original)` | `const copy = original.clone(); this.app.root.addChild(copy);` | | `Instantiate(prefab)` | `const instance = templateAsset.resource.instantiate(); this.app.root.addChild(instance);` | | `Destroy(gameObject)` | `entity.destroy()` | | `gameObject.SetActive(false)` | `entity.enabled = false` | | `gameObject.activeInHierarchy` | `entity.enabled`, which reads `false` when an ancestor is disabled | | `GetComponent()` | `entity.light` | | `GetComponent()` | `entity.script.spinner` | | `GetComponentInChildren()` | `entity.findComponent('light')` | | `GetComponentsInChildren()` | `entity.findComponents('light')` | | `AddComponent()` | `entity.addComponent('light', { type: 'omni' })` | | `Destroy(GetComponent())` | `entity.removeComponent('light')` | | `GameObject.Find("Player")` | `this.app.root.findByName('Player')` | | `GameObject.FindGameObjectsWithTag("Enemy")` | `this.app.root.findByTag('enemy')` | | `transform.Find("Arm/Hand")` | `entity.findByPath('Arm/Hand')` | | `CompareTag("Enemy")` | `entity.tags.has('enemy')` | `clone()` copies an entity's components and children, but its scripts start again from the attribute values they were created with. Values that a script has changed while the app runs are not copied, whereas Unity's `Instantiate` copies the current values of serialized fields. #### Transforms | Unity | PlayCanvas | | --- | --- | | `transform.position` | `entity.getPosition()`, `entity.setPosition(x, y, z)` | | `transform.localPosition` | `entity.getLocalPosition()`, `entity.setLocalPosition(x, y, z)` | | `transform.rotation` | `entity.getRotation()`, `entity.setRotation(quat)` | | `transform.eulerAngles` | `entity.getEulerAngles()`, `entity.setEulerAngles(x, y, z)` | | `transform.localScale` | `entity.getLocalScale()`, `entity.setLocalScale(x, y, z)` | | `transform.Translate(x, y, z)` | `entity.translateLocal(x, y, z)` (world space: `translate`) | | `transform.Rotate(x, y, z)` | `entity.rotateLocal(x, y, z)` (world space: `rotate`) | | `transform.LookAt(target)` | `entity.lookAt(target.getPosition())` | | `transform.forward`, `right`, `up` | `entity.forward`, `entity.right`, `entity.up` (`forward` is -Z) | | `transform.parent` | `entity.parent` | | `transform.SetParent(parent)` | `entity.reparent(parent)`, which keeps the local transform, so the entity moves with its new parent | | `transform.GetChild(i)`, `childCount` | `entity.children[i]`, `entity.children.length` | #### Time, Math and Debugging | Unity | PlayCanvas | | --- | --- | | `Time.deltaTime` | The `dt` argument of `update` | | `Time.timeScale` | `this.app.timeScale` | | `Time.time` | None. Add up `dt` in `update`. | | `Vector3`, `Quaternion`, `Color` | `Vec3`, `Quat`, `Color` | | `Vector3.up`, `Vector3.forward` | `Vec3.UP`, `Vec3.FORWARD` (which is `(0, 0, -1)`) | | `Quaternion.Euler(x, y, z)` | `new Quat().setFromEulerAngles(x, y, z)` | | `rotation * vector` | `rotation.transformVector(vector, result)` | | `Vector3.Distance(a, b)` | `a.distance(b)` | | `Vector3.Lerp(a, b, t)` | `result.lerp(a, b, math.clamp(t, 0, 1))`, because `lerp` doesn't clamp `t` | | `Mathf.Clamp`, `Mathf.Lerp` | `math.clamp`, `math.lerp` | | `Mathf.Deg2Rad` | `math.DEG_TO_RAD` | | `Random.Range(min, max)` with floats | `math.random(min, max)` | | `Random.Range(min, max)` with integers | `Math.floor(math.random(min, max))`, because `math.random` always returns a float | | `Debug.Log`, `LogWarning`, `LogError` | `console.log`, `console.warn`, `console.error` | | `Debug.DrawLine(start, end, color)` | `this.app.drawLine(start, end, color)` | #### Input | Unity | PlayCanvas | | --- | --- | | `Input.GetKey(KeyCode.W)` | `this.app.keyboard.isPressed(KEY_W)` | | `Input.GetKeyDown(KeyCode.W)` | `this.app.keyboard.wasPressed(KEY_W)` | | `Input.GetKeyUp(KeyCode.W)` | `this.app.keyboard.wasReleased(KEY_W)` | | `Input.GetMouseButton(0)` | `this.app.mouse.isPressed(MOUSEBUTTON_LEFT)` | | `Input.mousePosition` | The `x` and `y` of mouse events, measured from the top-left of the canvas rather than the bottom-left | | `Input.GetAxis("Mouse X")` | The `dx` of a `mousemove` event | | `Cursor.lockState = CursorLockMode.Locked` | `this.app.mouse.enablePointerLock()` | | `Input.touches` | Touch events on `this.app.touch` | | `Physics.Raycast` | `this.app.systems.rigidbody.raycastFirst(start, end)` | There are no input axes or action maps: read the devices directly, or map them to actions in a script of your own. Browsers only allow pointer lock in response to a click or key press. #### Web Platform | Unity | PlayCanvas | | --- | --- | | `PlayerPrefs` | The browser's [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) | | `UnityWebRequest` | [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) | | `JsonUtility` | `JSON.parse` and `JSON.stringify` | | `Application.OpenURL` | `window.open` | ### Vectors Are Objects Unity's `Vector3` and `Quaternion` are structs, copied whenever you assign them. PlayCanvas's `Vec3` and `Quat` are classes, so assignment shares one object, and JavaScript has no operator overloading. Three habits follow: - **Treat returned vectors as read-only.** Getters such as `entity.getPosition()` return a vector that the entity owns and reuses: its value changes when the entity moves, and writing to it does not update the entity properly. Call `clone()` to keep a value, and use setters such as `setPosition()` to change one. - **Use methods instead of operators.** Methods such as `add`, `sub` and `mulScalar` change the vector they are called on and return it. `add2(a, b)` and similar methods write a result into the vector they are called on. - **Avoid allocating in `update`.** Creating vectors every frame gives the garbage collector work that can cause stutters. Create them once and reuse them. ```javascript import { Script, Vec3 } from 'playcanvas'; export class Mover extends Script { static scriptName = 'mover'; /** @attribute */ speed = 5; // Created once, and reused every frame step = new Vec3(); update(dt) { // Unity: transform.position += transform.forward * speed * Time.deltaTime; this.step.copy(this.entity.forward).mulScalar(this.speed * dt); this.entity.translate(this.step); } } ``` ### Events and Messages C# events, `UnityEvent` and `SendMessage` all map to PlayCanvas [events](https://developer.playcanvas.com/user-manual/scripting/events.md). The application, entities and scripts can fire events and listen for them: ```javascript // Anywhere: fire an event on the application this.app.fire('player:died', this.entity); // In another script: listen for it, and stop listening when the script is destroyed initialize() { this.app.on('player:died', this.onPlayerDied, this); this.once('destroy', () => { this.app.off('player:died', this.onPlayerDied, this); }); } ``` Always remove listeners you add to other objects when your script is destroyed. Otherwise they keep running, and keep the script in memory. ### Coroutines and Timers PlayCanvas has no coroutines or `Invoke`. For gameplay timers, count down in `update`: the timer then honors `app.timeScale`, pauses while the script is disabled and stops when the entity is destroyed. ```javascript // Unity: Invoke(nameof(Spawn), 2f); initialize() { this.spawnTimer = 2; } update(dt) { if (this.spawnTimer > 0) { this.spawnTimer -= dt; if (this.spawnTimer <= 0) { this.spawn(); } } } ``` The browser's `setTimeout`, `setInterval` and `async` functions with `await` are useful for loading and other work that is not tied to game time, but they run in real time and keep running after the script is destroyed, so cancel them in a `destroy` handler. ### Execution Order Scripts on the same entity run in the order they are listed in its Script component, which you can change by dragging. Instead of depending on the order between entities, as Unity's Script Execution Order settings allow, use `postInitialize` and `postUpdate`, or events. ### Sharing Code and Using Packages Scripts are ES modules, so they share code through `import` and `export`. A module's top-level variables are shared by every script that imports it, which makes modules the place for what you would write as static classes and singletons in C#. They also survive scene changes. To use a package from npm in the Editor, map its name to a CDN URL with an [import map](https://developer.playcanvas.com/user-manual/editor/scripting/import-maps.md). Projects built [without the Editor](https://developer.playcanvas.com/user-manual/engine.md) install packages from npm like any other web project. ## Prefabs and Templates [Templates](https://developer.playcanvas.com/user-manual/editor/templates.md) are PlayCanvas's prefabs. They work much the same way: | Unity | PlayCanvas | | --- | --- | | Drag a GameObject into the Project window | Right-click an entity in the Hierarchy and select **Template** > **New Template** | | Prefab instance | Template instance, marked by its icon in the Hierarchy | | Overrides | [Overrides](https://developer.playcanvas.com/user-manual/editor/templates.md#template-overrides), shown in the Inspector, with a **View Diff** button | | **Overrides** > **Apply All** / **Revert All** | **Apply All** / **Revert All** in the Inspector of the instance's root | | Nested prefabs | [Nested templates](https://developer.playcanvas.com/user-manual/editor/templates/nested.md) | | Prefab Mode | Edit any instance in a scene, then apply its overrides | | Unpack Prefab | **Template** > **Unlink From Template** | | `Instantiate(prefab)` | `templateAsset.resource.instantiate()` | There are no prefab variants: a template instance with overrides is the closest equivalent. Importing a model creates a template of its hierarchy, much as Unity creates a model prefab. You cannot undo applying overrides to a template asset. To instantiate a template at runtime, its asset must be loaded: reference it from a script attribute with `@resource template` and either mark it to preload or [load it](https://developer.playcanvas.com/user-manual/assets/loading-unloading.md) first. ## Scenes | Unity | PlayCanvas | | --- | --- | | `SceneManager.LoadScene("Level 2")` | `this.app.scenes.changeScene('Level 2')` | | `LoadSceneMode.Additive` | `this.app.scenes.loadSceneHierarchy('Level 2', callback)` | | Unloading an additive scene | Destroy the root entity that `loadSceneHierarchy` passed to its callback | | `DontDestroyOnLoad` | None. See below. | | Lighting settings saved with each scene | Scene settings, applied by `changeScene` or `loadSceneSettings` | `changeScene` destroys every entity under the application root, including entities that your scripts created, before it adds the new scene. To keep entities alive from one level to the next, don't change scenes: load each level additively and destroy the previous level's root entity. Data that only scripts need can live in [modules](https://developer.playcanvas.com/user-manual/getting-started/migrating-from-unity.md#sharing-code-and-using-packages), which changing scenes doesn't affect. See [Loading Scenes](https://developer.playcanvas.com/user-manual/editor/scenes/loading-scenes.md). The Editor opens one scene at a time, so there is no equivalent of Unity's multi-scene editing. Loading scenes additively is something your app does when it runs. ## Assets The assets panel stores files much like the Project window, but projects live on PlayCanvas's servers rather than in a folder on your disk, so there are no `.meta` files. Each asset has an ID and an Inspector of its own for its import settings. | Unity | PlayCanvas | | --- | --- | | `Resources.Load("logo")` | `this.app.assets.find('logo', 'texture')`, then [load it](https://developer.playcanvas.com/user-manual/assets/loading-unloading.md) | | Addressables and AssetBundles | Assets that do not [preload](https://developer.playcanvas.com/user-manual/assets/preloading.md), loaded when you need them, found by name or [tag](https://developer.playcanvas.com/user-manual/assets/asset-registry.md#by-tag) | | ScriptableObject | A JSON asset, whose `resource` is the parsed object | | Texture import settings | The [texture inspector](https://developer.playcanvas.com/user-manual/editor/assets/inspectors/texture.md), including [texture compression](https://developer.playcanvas.com/user-manual/optimization/texture-compression.md) | | Model import settings | [Asset Import](https://developer.playcanvas.com/user-manual/editor/interface/settings/asset-import.md) settings | Assets marked **Preload** are downloaded before the application starts. New assets preload unless you turn off **Assets default to preload** in the Asset Import settings, so clear the option on large assets that only some scenes need. ## Rendering PlayCanvas has one renderer, so there is no render pipeline to choose. It renders with WebGPU or WebGL 2, and its [clustered lighting](https://developer.playcanvas.com/user-manual/graphics/lighting/clustered-lighting.md) keeps scenes with many omni and spot lights fast. ### Materials and Shaders The PlayCanvas [material](https://developer.playcanvas.com/user-manual/editor/assets/inspectors/material.md) is a physically based material like Unity's Standard shader and URP's Lit shader, with metalness and specular workflows: | Unity | PlayCanvas | | --- | --- | | Albedo or Base Map | Diffuse | | Metallic | Metalness | | Smoothness | Glossiness (higher is smoother in both) | | Normal Map | Normal | | Occlusion | Ambient Occlusion | | Emission | Emissive | | Rendering Mode: Cutout | Alpha Test | | Rendering Mode: Transparent or Fade | Blend Type, with Opacity | | Tiling and Offset | Tiling and Offset, for all maps or for each map | | Shader Graph and custom shaders | [Shaders](https://developer.playcanvas.com/user-manual/graphics/shaders.md) written in GLSL and WGSL | Unity's Metallic map holds metalness in its red channel and smoothness in its alpha channel. In PlayCanvas, assign the same texture to the **Metalness** map with channel R and to the **Glossiness** map with channel A. Check that the glossiness **Invert** option is off, because it makes the map act as a roughness map. ### Lighting | Unity | PlayCanvas | | --- | --- | | Directional light | Directional light | | Point light | Omni light | | Spot light | Spot light. Its Inner and Outer Cone Angles are measured from the light's axis, so they are half of Unity's Spot Angle. | | Area light | A light with a Rectangle, Disk or Sphere **Shape**, once **Area Lights Enabled** is on in Rendering Settings | | Lighting window environment settings, and fog | [Rendering Settings](https://developer.playcanvas.com/user-manual/editor/interface/settings/rendering.md): skybox, ambient color, exposure and fog | | Reflection probes | The skybox, which lights every material, and per-material cubemaps with box projection | | Light probes | None. Use lightmaps and environment lighting. | | Progressive Lightmapper | The [lightmapper](https://developer.playcanvas.com/user-manual/graphics/lighting/runtime-lightmaps.md), run from **Bake** on the toolbar, or in the running app | See [Lighting](https://developer.playcanvas.com/user-manual/graphics/lighting.md). ### Cameras and Layers | Unity | PlayCanvas | | --- | --- | | Culling Mask | Layers | | Depth, or URP camera stacking | Priority (lower values render first) | | Clear Flags | Clear Color Buffer and Clear Depth Buffer | | Viewport Rect | Viewport | | Target Texture | `renderTarget`, set from a script | | Orthographic Size | Ortho Height | A Unity GameObject sits on exactly one layer, and layers drive rendering, physics and ray casts alike. PlayCanvas [layers](https://developer.playcanvas.com/user-manual/graphics/layers.md) are for rendering only. They decide which cameras draw a mesh and in what order: each camera renders the layers in its list, in the order set in **Settings** > **Layers**, and components that draw meshes can be on more than one layer. Physics filters with [collision groups and masks](https://developer.playcanvas.com/user-manual/physics/rigid-bodies.md#collision-groups-and-masks) instead. See [Multiple Cameras](https://developer.playcanvas.com/user-manual/graphics/cameras/multiple-cameras.md). ### Post-Processing Unity's post-processing volumes correspond to [`CameraFrame`](https://developer.playcanvas.com/user-manual/graphics/posteffects/cameraframe.md), which adds bloom, ambient occlusion, depth of field, anti-aliasing, color grading, vignette and more to a camera. In the Editor, add the [CameraFrame script](https://developer.playcanvas.com/user-manual/graphics/linear-workflow/hdr-rendering.md#cameraframe-in-the-editor) to your camera entity. Like any script, it only runs in the launched app, so the effects don't appear in the viewport. Without it, tone mapping and gamma are properties of the Camera component. ### Performance Features | Unity | PlayCanvas | | --- | --- | | Static and dynamic batching | [Batch groups](https://developer.playcanvas.com/user-manual/graphics/advanced-rendering/batching.md) | | GPU instancing | [Hardware instancing](https://developer.playcanvas.com/user-manual/graphics/advanced-rendering/hardware-instancing.md) | | Occlusion culling | None. Cameras cull meshes outside their view. | | LOD Group | None for meshes | | Profiler | See [Debugging and Profiling](https://developer.playcanvas.com/user-manual/getting-started/migrating-from-unity.md#debugging-and-profiling) | ## Physics PlayCanvas physics runs on [ammo.js](https://github.com/kripken/ammo.js), a WebAssembly build of the Bullet physics engine. It is opt-in: to add it to a project, open **Settings**, expand **PHYSICS** and click **IMPORT AMMO**. Gravity is set in the same section, for each scene. See [Physics](https://developer.playcanvas.com/user-manual/physics.md). | Unity | PlayCanvas | | --- | --- | | Rigidbody | Rigid Body component of type Dynamic | | Rigidbody with **Is Kinematic** | Rigid Body of type Kinematic | | Collider without a Rigidbody | Collision component **and** a Rigid Body of type Static | | Collider with **Is Trigger** | Collision component without a Rigid Body | | `AddForce(force)` | `entity.rigidbody.applyForce(force)` | | `AddForce(force, ForceMode.Impulse)` | `entity.rigidbody.applyImpulse(force)` | | `AddTorque` | `applyTorque`, `applyTorqueImpulse` | | `velocity` (`linearVelocity` in Unity 6) | `linearVelocity` | | Setting a dynamic body's position | `entity.rigidbody.teleport(position)` | | `MovePosition` on a kinematic body | Set the entity's position: kinematic bodies follow their entity | | Constraints (freeze position or rotation) | Linear Factor and Angular Factor | | Physic Material | Friction and Restitution on the Rigid Body | | `OnCollisionEnter`, `OnCollisionStay`, `OnCollisionExit` | `collisionstart`, `contact` and `collisionend` events on the collision component | | `OnTriggerEnter`, `OnTriggerExit` | `triggerenter` and `triggerleave` events, on the trigger's collision component and on the rigid body that enters it | | Layer collision matrix | [Collision groups and masks](https://developer.playcanvas.com/user-manual/physics/rigid-bodies.md#collision-groups-and-masks), set from a script | | `Physics.Raycast` | [`raycastFirst` and `raycastAll`](https://developer.playcanvas.com/user-manual/physics/ray-casting.md) | | Character Controller | None. Drive a dynamic rigid body from a script. | These differences catch out most Unity developers: - **Static colliders need a rigid body.** A collision component on its own is a [trigger volume](https://developer.playcanvas.com/user-manual/physics/trigger-volumes.md), which detects bodies but does not stop them. Give floors and walls a Rigid Body component of type Static. - **Primitive collision shapes ignore scale.** A box, sphere or capsule shape keeps its Half Extents or Radius however you scale its entity. Mesh shapes are the exception. See [Scale](https://developer.playcanvas.com/user-manual/physics/collision-shapes.md#scale). - **There is no `FixedUpdate`.** The simulation steps at a fixed rate of 60 times a second, and you apply forces from `update`. Collision events fire once per physics step. - **Physics owns dynamic bodies.** After each step the engine writes the position and rotation of every dynamic body to its entity, so move dynamic bodies with forces, velocities or `teleport`, rather than by setting the entity's transform. ## User Interface PlayCanvas's in-canvas UI works much like Unity's UI (uGUI). See [User Interface](https://developer.playcanvas.com/user-manual/user-interface.md). | Unity | PlayCanvas | | --- | --- | | Canvas in Screen Space - Overlay | [Screen](https://developer.playcanvas.com/user-manual/user-interface/screens.md) component with **Screen Space** enabled | | Canvas in World Space | Screen component with **Screen Space** disabled | | Canvas Scaler: Scale With Screen Size | **Scale Mode** Blend, with a **Ref Resolution** and **Scale Blend** | | RectTransform | [Element](https://developer.playcanvas.com/user-manual/user-interface/elements.md) component: anchor, pivot and margins | | Image, Raw Image | Element of type Image, showing a texture or a sprite | | Text, TextMeshPro | Element of type Text, with a [font](https://developer.playcanvas.com/user-manual/user-interface/fonts.md) asset made from a TTF or OTF file | | Button | [Button](https://developer.playcanvas.com/user-manual/user-interface/buttons.md) component | | Horizontal, Vertical and Grid Layout Group | [Layout Group](https://developer.playcanvas.com/user-manual/user-interface/layout-groups.md) component | | Layout Element | Layout Child component | | Scroll Rect, Scrollbar | [Scroll View](https://developer.playcanvas.com/user-manual/user-interface/scroll-views.md) and Scrollbar components | | Mask, Rect Mask 2D | An element with **Mask** enabled. See [Masks](https://developer.playcanvas.com/user-manual/user-interface/masks.md). | | EventSystem and Graphic Raycaster | Enable **Use Input** on the elements that should receive [input](https://developer.playcanvas.com/user-manual/user-interface/input.md) | | Toggle, Slider, Dropdown | Built from elements. See [Common Widgets](https://developer.playcanvas.com/user-manual/user-interface/common-widgets.md). | | UI Toolkit | [HTML and CSS](https://developer.playcanvas.com/user-manual/user-interface/html-and-css.md) | Because your app runs in a web page, you can also build any part of the interface in HTML and CSS, laid over the canvas. Text input fields and accessible menus are easier to build that way. ## Animation | Unity | PlayCanvas | | --- | --- | | Animator component | [Anim](https://developer.playcanvas.com/user-manual/animation/playing-animations.md) component | | Animator Controller | [Anim state graph](https://developer.playcanvas.com/user-manual/animation/state-graphs.md) asset, with states, transitions, parameters and layers | | Animation Clip | Animation asset, created when you import a model | | `animator.SetFloat("Speed", 2f)` | `entity.anim.setFloat('Speed', 2)` | | `SetBool`, `SetInteger`, `SetTrigger` | `setBoolean`, `setInteger`, `setTrigger` | | Avatar Mask | [Layer mask](https://developer.playcanvas.com/user-manual/animation/layers-and-masks.md) | | Blend Tree | [Blend trees](https://developer.playcanvas.com/user-manual/animation/blend-trees.md) (1D, 2D and direct), in state graphs created from code. The Editor's state graph editor has none. | | Root Motion | None. Move the entity from a script. | | Animation Events | [Anim events](https://developer.playcanvas.com/user-manual/animation/events.md) on the animation asset | | Animator Override Controller | One anim state graph, with different animation assets assigned to its states on each entity | PlayCanvas has no humanoid retargeting. An animation drives bones by name, so it plays on any model whose bones have the same names, but nothing adapts it to a skeleton with different proportions. Author or bake animations for the skeleton they play on. ## Audio | Unity | PlayCanvas | | --- | --- | | Audio Source | A slot on a [Sound](https://developer.playcanvas.com/user-manual/editor/scenes/components/sound.md) component | | `audioSource.Play()` | `entity.sound.play('slot name')` | | Spatial Blend set to 3D | **Positional** on the Sound component | | Min Distance and Max Distance | Ref Distance and Max Distance | | Volume Rolloff | Distance Model, which defaults to Linear where Unity defaults to Logarithmic | | Audio Listener | Audio Listener component | | Audio Mixer | None. Use the [Web Audio API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API). | Browsers do not play sound until the user has interacted with the page, for example by clicking or pressing a key, so start music and other sounds after the first click. ## Bringing Your Content Over There is no automatic converter from Unity projects. Assets come across through standard file formats, and code is rewritten. - **Models and animations.** Export them as GLB files with a glTF exporter such as [UnityGLTF](https://github.com/KhronosGroup/UnityGLTF) or Unity's glTFast package, or as FBX with Unity's FBX Exporter package. The Editor imports the binary `.glb` form of glTF, not `.gltf`. Drag the files into the assets panel: FBX files are converted to GLB, and each model produces render, material, texture and animation assets, plus a template of its hierarchy. See [Importing 3D Models](https://developer.playcanvas.com/user-manual/assets/models.md). - **Materials.** Unity shaders do not carry over. glTF exporters convert Standard and URP Lit materials to glTF's PBR materials, which import as PlayCanvas materials. FBX files carry less, so expect to set up FBX materials again. - **Textures, audio and fonts.** Upload the source files. See [Supported Formats](https://developer.playcanvas.com/user-manual/assets/supported-formats.md). - **Scenes and prefabs.** Export the static geometry of a scene as a single GLB to keep its layout, then add lights, cameras, physics, UI and scripts in the Editor. - **Terrain.** Convert terrain to a mesh before you export it. - **Scripts and shaders.** Rewrite them in JavaScript and in GLSL or WGSL. AI coding assistants are good at translating MonoBehaviours. To let one work on your Editor project's scripts, sync them with the [VS Code extension](https://developer.playcanvas.com/user-manual/editor/scripting/vscode-extension.md), and connect it to the Editor with the [MCP Server](https://developer.playcanvas.com/user-manual/editor/mcp-server.md) to let it edit scenes too. - **Lightmaps.** Bake them again with the PlayCanvas lightmapper, or bake them in a 3D modeling tool and import them with the model. ## Publishing Unity builds a player for each platform. PlayCanvas publishes a web app, made of HTML, JavaScript and your assets: - **Publish** hosts the build on PlayCanvas and gives it a URL to share. See [PlayCanvas Hosting](https://developer.playcanvas.com/user-manual/editor/publishing/web/playcanvas-hosting.md). - **Download** creates a ZIP file to [host yourself](https://developer.playcanvas.com/user-manual/editor/publishing/web/self-hosting.md). - For app stores, wrap the web app for [mobile](https://developer.playcanvas.com/user-manual/editor/publishing/mobile.md) or [desktop](https://developer.playcanvas.com/user-manual/editor/publishing/desktop.md), or publish it as a [playable ad](https://developer.playcanvas.com/user-manual/editor/publishing/playable-ads.md). ## Debugging and Profiling Your app runs in the browser, so you debug it with the browser's developer tools (F12, or Cmd+Option+I on macOS) in the launched tab. | Unity | PlayCanvas | | --- | --- | | Console window | The **Console** tab of the developer tools. See [Console Logging](https://developer.playcanvas.com/user-manual/debugging/console-logging.md). | | Attaching Visual Studio or Rider | Breakpoints in the **Sources** tab of the developer tools. See [Browser Dev Tools](https://developer.playcanvas.com/user-manual/debugging/browser-dev-tools.md). | | `Debug.Break()` | A `debugger;` statement, which pauses the app while the developer tools are open | | Profiler | The [Profiler](https://developer.playcanvas.com/user-manual/optimization/profiler.md) and [MiniStats](https://developer.playcanvas.com/user-manual/optimization/mini-stats.md), from the Launch button's menu, and the **Performance** tab of the developer tools | | Frame Debugger | The [Inspector](https://developer.playcanvas.com/user-manual/debugging/inspector.md), also from the Launch button's menu, which shows the render passes and draw calls of each frame, and [native GPU profilers](https://developer.playcanvas.com/user-manual/optimization/gpu-profiling.md) | | `Debug.DrawLine` and Gizmos | `this.app.drawLine()`, and [`WireRenderer`](https://developer.playcanvas.com/user-manual/graphics/debug-drawing.md) for spheres, boxes and other shapes | ## Version Control and Collaboration A Unity project is a folder that you put under version control. A PlayCanvas project is shared online: when teammates open a scene, they [edit it together](https://developer.playcanvas.com/user-manual/editor/realtime-collaboration.md) in real time and see each other's changes as they happen. History is kept with the Editor's [version control](https://developer.playcanvas.com/user-manual/editor/version-control.md): create [checkpoints](https://developer.playcanvas.com/user-manual/editor/version-control/checkpoints.md) as you would commits, work on [branches](https://developer.playcanvas.com/user-manual/editor/version-control/branches.md), and [merge](https://developer.playcanvas.com/user-manual/editor/version-control/merging.md) them with conflict resolution. ## Features Without a Built-in Equivalent | Unity | Alternative in PlayCanvas | | --- | --- | | Terrain | Import terrain as meshes | | NavMesh and AI Navigation | A library such as [recast-navigation-js](https://github.com/isaac-mason/recast-navigation-js), which supports PlayCanvas | | Character Controller | A dynamic rigid body driven by a script, or the engine's first-person and third-person controller scripts | | 2D physics | 3D physics with the third axis locked by Linear Factor and Angular Factor | | Timeline and Cinemachine | Scripts, with [curve](https://developer.playcanvas.com/user-manual/scripting/script-attributes/esm.md#curve-attribute) attributes for animated values | | VFX Graph | The [Particle System](https://developer.playcanvas.com/user-manual/graphics/particles.md) component | | Light probes and realtime global illumination | Lightmaps and environment lighting | | Tweening packages, such as DOTween | A JavaScript tweening library, imported from a CDN | ## Next Steps - [Your First App](https://developer.playcanvas.com/user-manual/editor/getting-started/your-first-app.md) - Build a scene in the Editor. - [Scripting](https://developer.playcanvas.com/user-manual/scripting.md) - Learn the scripting system in depth. - [Templates](https://developer.playcanvas.com/user-manual/editor/templates.md) - Reuse entities across scenes. - [Tutorials](https://developer.playcanvas.com/tutorials/) - Follow step-by-step projects. - [Forum](https://forum.playcanvas.com) and [Discord](https://discord.gg/RSaMRzg) - Ask the community and the PlayCanvas team. -------------------------------------------------------------------------------- ## Join the PlayCanvas Community URL: https://developer.playcanvas.com/user-manual/getting-started/community/ Markdown: https://developer.playcanvas.com/user-manual/getting-started/community.md To get the most out of PlayCanvas, we recommend that you join our community! ๐Ÿค **Make friends** with other community members including the dev team that builds PlayCanvas ๐ŸŽ“ **Learn** from other PlayCanvas experts ๐ŸŽจ **Share your creations** with people who care ๐Ÿ“ฐ **Stay informed** about the latest PlayCanvas-related news ## Our Community Platforms We focus on 5 key community platforms: ### [Reddit](https://reddit.com/) Reddit is a great place to share PlayCanvas work, ask questions, and connect with people who've proactively opted into a PlayCanvas-related community. To join: * Visit our [subreddit](https://www.reddit.com/r/PlayCanvas/). * Click the 'Join' button. * Optional: Tap the **bell** to set notification frequency (we recommend **Low** which is Reddit's default). :::tip[tips for posting] * An **Image & Video** post will perform much better than a **Text** post. * Try **crossposting** your PlayCanvas posts to related subreddits such as [WebGL](https://www.reddit.com/r/webgl/), [WebGPU](https://www.reddit.com/r/webgpu/) and [WebXR](https://www.reddit.com/r/WebXR/) - but always read each subreddit's rules first! To crosspost, select **Share** > **Repost** underneath your post, then choose the target community. ::: ### [X](https://x.com/) X (formerly Twitter) is ideal for quick updates, launch announcements, short clips, and real-time conversations with the wider web graphics community. To join: * Visit our [official X account](https://x.com/playcanvas). * Tap the **Follow** button. * Optional: Tap the bell to enable notifications. :::tip[tips for posting] * Attach a video to your post (GIF or short MP4, aim to stay below ~30s) for best reach. * Tagging **@playcanvas** in your posts dramatically boosts the chance that the PlayCanvas team will repost you. * Adding a link to your post will limit its reach. You can mitigate this by adding a link to the end of a thread. ::: ### [LinkedIn](https://linkedin.com/) LinkedIn is perfect for professional networking, sharing career achievements, and connecting with industry professionals in the web graphics space. To join: * Visit our [company page](https://www.linkedin.com/company/playcanvas/). * Tap the **+ Follow** button. * Optional: Click **Turn on** to receive post notifications from us. :::tip[tips for posting] * Share professional milestones like project launches, career updates, or technical insights. * Use industry-relevant hashtags like **#gamedev**, **#webgl**, **#javascript**, and **#playcanvas**. * Professional posts with project screenshots or videos tend to generate good engagement and networking opportunities. ::: ### [Forum](https://forum.playcanvas.com/) The PlayCanvas Forum is the best place for detailed technical discussions, troubleshooting complex issues, and sharing comprehensive tutorials with the community. To join: * Visit the [PlayCanvas Forum](https://forum.playcanvas.com/). * Tap **Sign Up** to create your account. * Optional: Enable email notifications for topics you're interested in following. :::tip[tips for posting] * **Search first** - Many questions have been answered before. Use the search function to check existing topics. * **Be specific** - Include details like browser version, error messages, and relevant code snippets when asking for help. * **Use proper categories** - Post in the appropriate section (Help & Support, Showcase, Jobs, etc.) to reach the right audience. ::: ### [Discord](https://discord.gg/RSaMRzg) Discord provides real-time chat for quick questions, casual conversations, and connecting with community members and the PlayCanvas team in an informal setting. To join: * Visit our [Discord server](https://discord.gg/RSaMRzg). * Tap **Accept Invite** to join the server. * Optional: Customize your notification settings for different channels based on your interests. :::tip[tips for chatting] * **Use appropriate channels** - Post in the right channel to keep conversations organized. For example, we have a dedicated channel on Gaussian Splatting. * **Be respectful** - We are proud to run a kind, friendly and helpful community. * **Share screenshots and links** - Visual problems are much easier to diagnose when you can show what's happening. ::: -------------------------------------------------------------------------------- ## Open Source Mission URL: https://developer.playcanvas.com/user-manual/getting-started/open-source/ Markdown: https://developer.playcanvas.com/user-manual/getting-started/open-source.md ## Mission Statement > PlayCanvas is committed to democratizing 3D web development through open source technology. Our mission is to make powerful, interactive 3D experiences accessible to everyone, regardless of background or budget, by providing free, open, and well-documented tools that anyone can use, modify, and contribute to. ## Why Open Source? At PlayCanvas, we believe that the future of the web is interactive and three-dimensional. By open sourcing our core technologies, we aim to: **๐ŸŒ Democratize 3D Development**: Remove barriers to entry and make advanced 3D web technologies accessible to developers worldwide, regardless of their financial resources. **๐Ÿ”ง Foster Innovation**: Enable the community to extend, modify, and improve our tools, leading to innovations we never could have imagined alone. **๐Ÿค Build Trust**: Transparency in our codebase allows developers to understand exactly how our tools work, contributing to trust and reliability. **๐Ÿ“š Advance the Industry**: By sharing our knowledge and code, we help push the entire 3D web development ecosystem forward. **๐ŸŒฑ Ensure Longevity**: Open source ensures that our tools will continue to exist and evolve, even as our company changes and grows. ## Our Home on GitHub We use GitHub to manage our open source projects. Visit our [GitHub organization](https://github.com/playcanvas) to explore our complete open source ecosystem. :::tip Stay informed Hit the **Follow** button on our [organization page](https://github.com/playcanvas) to add our activity to your personal dashboard! ::: Here are some of our key repositories: | Repository | Description | License | | ---------- | ----------- | ------- | | [**engine**](https://github.com/playcanvas/engine) | JavaScript runtime for 3D web applications | MIT | | [**editor**](https://github.com/playcanvas/editor) | Visual editing environment for building WebGL/WebGPU/WebXR applications | MIT | | [**react**](https://github.com/playcanvas/react) | React components for building declarative 3D scenes | MIT | | [**web-components**](https://github.com/playcanvas/web-components) | Web Components for standards-based 3D development | MIT | | [**supersplat**](https://github.com/playcanvas/supersplat) | SuperSplat Editor โ€” browser-based editor for 3D Gaussian Splats | MIT | | [**supersplat-viewer**](https://github.com/playcanvas/supersplat-viewer) | SuperSplat Viewer โ€” open-source viewer for published splats, embeddable via npm | MIT | | [**splat-transform**](https://github.com/playcanvas/splat-transform) | CLI and library for converting, transforming, and analyzing splats | MIT | | [**model-viewer**](https://github.com/playcanvas/model-viewer) | glTF and 3D Gaussian Splat viewer | MIT | | [**pcui**](https://github.com/playcanvas/pcui) | Comprehensive UI library for building browser-based tools | MIT | :::tip Even this website is [open sourced under MIT](https://github.com/playcanvas/developer-site). Would you like to contribute and make it even better? Be our guest! ::: ## Contributing to PlayCanvas We welcome contributions from developers of all skill levels! Whether you're fixing a typo in our documentation or implementing a major new feature, your contributions help make PlayCanvas better for everyone. ### Getting Started 1. **Choose Your Area of Interest**: Browse our repositories and find something that interests you 2. **Check Existing Issues**: If you are just starting out, look for ["good first issue"](https://github.com/search?q=org%3Aplaycanvas+label%3A%22good+first+issue%22&type=issues) labels across our repositories 3. **Start a Discussion**: Open an issue to discuss your ideas before implementing major changes 4. **Read the Guidelines**: Each repository has specific contributing guidelines in its `CONTRIBUTING.md` file ### Contribution Process #### 1. **Log Issues** - **Bug Reports**: Found a bug? [Create a detailed issue](https://github.com/playcanvas/engine/issues/new) with reproduction steps - **Feature Requests**: Have an idea? Share it in the relevant repository's issues - **Questions**: Use [GitHub Discussions](https://github.com/playcanvas/engine/discussions) for general questions #### 2. **Submit Pull Requests** - **Discussion First**: For significant changes, open an issue for discussion before coding - **Follow Guidelines**: Each repository has specific code style and contribution guidelines - **Stay Focused**: Keep PRs small and focused on a single feature or fix - **Include Tests**: Add or update tests when appropriate - **Complete CLA**: Sign our [Contributor License Agreement](https://docs.google.com/a/playcanvas.com/forms/d/1Ih69zQfJG-QDLIEpHr6CsaAs6fPORNOVnMv5nuo0cjk/viewform) #### 3. **Review Process** - Our maintainers will review your PR and provide feedback - Address any requested changes promptly - Be patientโ€”quality reviews take time, but they ensure code quality ## Supporting PlayCanvas ### Star Our Repositories โญ One of the simplest ways to support PlayCanvas is by starring our repositories! Stars help: - **Increase Visibility**: More stars mean more developers discover our tools - **Show Appreciation**: Let us know which projects you find valuable - **Track Popularity**: Help us understand which tools are most important to the community **Our Top Repos to Star**: - [PlayCanvas Engine](https://github.com/playcanvas/engine) โญ - [PlayCanvas React](https://github.com/playcanvas/react) โญ - [PlayCanvas Web Components](https://github.com/playcanvas/web-components) โญ - [SuperSplat](https://github.com/playcanvas/supersplat) โญ ### Watch Repositories for Updates ๐Ÿ‘€ Stay informed about PlayCanvas development by watching repositories of interest: #### What You'll Receive - **Issue Notifications**: Get notified when new bugs are reported or feature requests are made - **Pull Request Updates**: See when new features are being developed - **Release Announcements**: Be the first to know about new versions and features - **Discussion Alerts**: Participate in important design and architecture discussions #### How to Watch 1. Visit any PlayCanvas repository on GitHub 2. Click the "Watch" button (๐Ÿ‘๏ธ) at the top right 3. Choose your notification level: - **All Activity**: Get notified about everything - **Issues, PRs, Releases**: Only important updates - **Releases Only**: Just new version announcements #### Recommended Watches - [Engine](https://github.com/playcanvas/engine/subscription) - Core runtime updates - ...and any other [repositories](https://github.com/playcanvas) you actively use in your projects! ## Final Thoughts When you contribute to PlayCanvas, you're not just improving software โ€” you're helping to build the future of interactive web experiences. Every bug fix, feature request, documentation improvement, and star helps make 3D web development more accessible to developers everywhere. **Ready to contribute?** Start by exploring our [GitHub organization](https://github.com/playcanvas) and find a project that interests you. The PlayCanvas community is here to help you get started! ๐Ÿ™Œ -------------------------------------------------------------------------------- ## Made with PlayCanvas URL: https://developer.playcanvas.com/user-manual/getting-started/made-with-playcanvas/ Markdown: https://developer.playcanvas.com/user-manual/getting-started/made-with-playcanvas.md Below is our showcase video of some of the best WebGL browser games and experiences made with PlayCanvas. Find more fantastic games and experiences made by our users in the [PlayCanvas Awesome List](https://github.com/playcanvas/awesome-playcanvas)! ## PlayCanvas Showcase 2022 Links to the content showcased can be found on the [blog post](https://blog.playcanvas.com/our-2022-developer-showreel-is-live/). [Video: YouTube video player](https://www.youtube.com/embed/46f73gp1_TU) ## PlayCanvas Showcase 2021 Links to the content showcased can be found on the [blog post](https://blog.playcanvas.com/playcanvas-showcase-2021/). [Video: YouTube video player](https://www.youtube.com/embed/FrUUrVRpbzg) -------------------------------------------------------------------------------- ## PlayCanvas Engine URL: https://developer.playcanvas.com/user-manual/engine/ Markdown: https://developer.playcanvas.com/user-manual/engine.md The PlayCanvas Engine is an open-source 3D engine for the web. It renders with WebGPU or WebGL 2 in any modern browser, on desktop and mobile, and it's the foundation that the [Editor](https://developer.playcanvas.com/user-manual/editor.md), [PlayCanvas React](https://developer.playcanvas.com/user-manual/react.md) and [Web Components](https://developer.playcanvas.com/user-manual/web-components.md) are built on. [Interactive demo: Tropical islands with palm trees on a rippling turquoise sea](https://playcanvas.com/examples/iframe/graphics_water.html) [Get Started โ†’](https://developer.playcanvas.com/user-manual/engine/standalone.md) [Browse the Examples](https://playcanvas.com/examples/) [API Reference](https://api.playcanvas.com/engine/) ## Your First App This is a complete Engine app. It is running right here in the page, and you can edit it: the preview reruns as you type. ```js live-example import { AppBase, AppOptions, CameraComponentSystem, Color, createGraphicsDevice, DEVICETYPE_WEBGPU, Entity, FILLMODE_FILL_WINDOW, LightComponentSystem, RenderComponentSystem, RESOLUTION_AUTO, StandardMaterial } from 'playcanvas'; // create a graphics device, preferring WebGPU over WebGL 2 const canvas = document.getElementById('application'); const device = await createGraphicsDevice(canvas, { deviceTypes: [DEVICETYPE_WEBGPU] }); device.maxPixelRatio = Math.min(window.devicePixelRatio, 2); // create an application with the component systems it uses const options = new AppOptions(); options.graphicsDevice = device; options.componentSystems = [ RenderComponentSystem, CameraComponentSystem, LightComponentSystem ]; const app = new AppBase(canvas); app.init(options); app.setCanvasFillMode(FILLMODE_FILL_WINDOW); app.setCanvasResolution(RESOLUTION_AUTO); window.addEventListener('resize', () => app.resizeCanvas()); app.start(); // light the scene softly from all around app.scene.ambientLight = new Color(0.3, 0.3, 0.35); // create a camera looking down at the middle of the grid const camera = new Entity('camera'); camera.addComponent('camera', { clearColor: new Color(0.12, 0.14, 0.17) }); camera.setPosition(0, 7, 17); camera.lookAt(0, 0, 0); app.root.addChild(camera); // create a sun that casts shadows const light = new Entity('light'); light.addComponent('light', { castShadows: true, shadowDistance: 40, shadowBias: 0.2, normalOffsetBias: 0.05 }); light.setEulerAngles(45, 30, 0); app.root.addChild(light); // create a grid of boxes, shading from orange in the middle to purple at the edges const size = 10; const orange = new Color(1, 0.4, 0.1); const purple = new Color(0.4, 0.2, 1); const boxes = []; for (let x = -size; x <= size; x++) { for (let z = -size; z <= size; z++) { const material = new StandardMaterial(); material.diffuse.lerp(orange, purple, Math.hypot(x, z) / (size * 1.5)); material.update(); const box = new Entity(); box.addComponent('render', { type: 'box', material: material }); box.setPosition(x, 0, z); app.root.addChild(box); boxes.push(box); } } // every frame, ripple the boxes' heights out from the middle let time = 0; app.on('update', (dt) => { time += dt; for (const box of boxes) { const { x, z } = box.getPosition(); const height = 2.2 + 2 * Math.sin(time * 3 - Math.hypot(x, z) * 0.5); box.setLocalScale(0.9, height, 0.9); } }); ``` The first lines are the same in every Engine app. [`createGraphicsDevice`](https://api.playcanvas.com/engine/functions/createGraphicsDevice.html) asks for WebGPU and falls back to WebGL 2 where the browser doesn't support it. [`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.html) is the application: it runs the frame loop, but only the component systems you register, so a bundler can leave the others out of your build. Everything in the scene is an [entity](https://developer.playcanvas.com/user-manual/ecs/entities.md) in a hierarchy under `app.root`, and components give each entity its abilities: here a camera, a sun that casts shadows, and 441 boxes, each rendered with its own [material](https://developer.playcanvas.com/user-manual/graphics/physical-rendering/physical-materials.md). Every frame, the `update` event passes your code the time since the last one, which it uses to ripple the boxes. Some things to try: - Speed the ripple up by raising the `3` in `time * 3`, or tighten its rings by raising the `0.5`. - Swap `orange` and `purple` for any two colors you like. - Grow the grid by changing `size` to `20`: that's 1,681 boxes. - Turn the boxes into columns with `type: 'cylinder'`. To build an app like this on your own machine, run `npm create playcanvas@latest` and pick the Engine format, or follow [Using the Engine Standalone](https://developer.playcanvas.com/user-manual/engine/standalone.md) to set a project up by hand. ## What You Can Build Engine apps run in the browser, so whatever you build is a link away for anyone, on any device. These are some of the things developers build with it: [A catapult on a grassy slope launching a burning boulder at soldiers in a valley](https://playcanvas.com/examples/#/demos/catapult): GamesBrowser and mobile games that start from a link, with nothing to install. This siege game is built entirely with the engine. Play the demo โ†’ [A blue running shoe beside a panel of style options](https://playcanvas.com/examples/#/misc/html-texture-configurator): Product ConfiguratorsLet shoppers restyle a product in real time. This shoe switches between glTF material variants from an HTML panel rendered in 3D. Try the demo โ†’ [A Gaussian splat capture of a skate park surrounded by trees](https://playcanvas.com/examples/#/gaussian-splatting/world): Gaussian Splat AppsViewers, tours and games built on photoreal captures. This skate park streams in by level of detail as you move. Explore the demo โ†’ [Two tracked hands in VR, each casting a pointer ray](https://developer.playcanvas.com/user-manual/xr.md): XR AppsVR and AR that open straight from a link with WebXR, on headsets and phones, with controller and hand tracking. Read the XR guide โ†’ [The catapult game running in portrait on a phone](https://developer.playcanvas.com/user-manual/editor/publishing/playable-ads.md): Playable AdsPackage a game like the catapult as an interactive ad, and export it from the Editor for Facebook and Snapchat. Publish a playable ad โ†’ [The Sun beside a panel of facts about it](https://playcanvas.github.io/web-components/examples/#solar-system.html): EducationInteractive lessons and explainers. This scroll-driven tour of the solar system is a single HTML page built with Web Components. Explore the demo โ†’ The [examples browser](https://playcanvas.com/examples/) has more than 250 live examples, from volumetric fog and dynamic skies to crowds of thousands of animated characters, each with source code you can edit. Models: [Tropical Island](https://sketchfab.com/3d-models/tropical-island-f91862f8c38b481aa19edccac851eefb) by Elin (in the demo at the top of the page), [Catapult](https://sketchfab.com/3d-models/atapult-1c33623dbe0049b98be97a750f27b51b) by AlexJJ, [Low Poly Lumberjack](https://sketchfab.com/3d-models/low-poly-lumberjack-a93a29105fc44bf594f8100b7726bcec) by Daz and [Materials Variants Shoe](https://github.com/KhronosGroup/glTF-Sample-Assets/tree/main/Models/MaterialsVariantsShoe) by Shopify, all [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). Skatepark splat by [Christoph Schindelar](https://superspl.at/user?id=schindelar3d). ## Why the PlayCanvas Engine? - **WebGPU and WebGL 2 from one codebase.** Ask for WebGPU and the engine falls back to WebGL 2 in browsers that don't support it yet, with the same API and the same look. See [Supported Browsers](https://developer.playcanvas.com/user-manual/engine/supported-browsers.md) for where each one runs. - **Batteries included.** Rigid-body [physics](https://developer.playcanvas.com/user-manual/physics.md), state-based [animation](https://developer.playcanvas.com/user-manual/animation.md), positional sound, 2D and 3D [user interfaces](https://developer.playcanvas.com/user-manual/user-interface.md), [WebXR](https://developer.playcanvas.com/user-manual/xr.md) for AR and VR, [Gaussian splats](https://developer.playcanvas.com/user-manual/gaussian-splatting.md), and mouse, keyboard, touch and gamepad input are all built in. The package also ships [ready-made scripts](https://github.com/playcanvas/engine/tree/main/scripts/esm) for camera controls, character controllers, XR, post effects and more. - **Lean by design.** The engine is published as ES modules, and `AppBase` runs only the component systems and resource handlers you register, so a bundler can leave out the ones your app doesn't use. - **Assets that load fast.** Models load from [glTF 2.0](https://developer.playcanvas.com/user-manual/assets/supported-formats.md) files with Draco geometry and Basis texture compression, and large Gaussian splat scenes [stream in by level of detail](https://developer.playcanvas.com/user-manual/gaussian-splatting/building/lod-streaming.md) as the camera moves. - **TypeScript ready.** The npm package ships complete TypeScript declarations, so your editor can complete and check every class, method and property, whether you write TypeScript or JavaScript. - **Runs where JavaScript runs.** As well as in the browser, the engine [runs headless in Node.js](https://developer.playcanvas.com/user-manual/engine/running-in-node.md), for multiplayer servers, asset tools and unit tests. - **Open source and proven in production.** The engine is developed in the open [on GitHub](https://github.com/playcanvas/engine) under the MIT license, free for personal and commercial projects. It powers the PlayCanvas Editor and [SuperSplat](https://developer.playcanvas.com/user-manual/supersplat.md), as well as every app built with the Editor, PlayCanvas React or Web Components. ## One Engine, Four Ways to Use It Every PlayCanvas product drives this engine, so choose the way of working that suits you. What you learn about entities, components, materials and scripts carries over between them. [๐Ÿฆพ Write code against the Engine](https://developer.playcanvas.com/user-manual/engine/standalone.md): Create the app, its entities and their components yourself in JavaScript or TypeScript, with full control over the frame loop and every system. Using the Engine Standalone โ†’ [๐Ÿ› ๏ธ Build visually in the Editor](https://developer.playcanvas.com/user-manual/editor.md): Compose scenes with your team in a browser-based editor, and attach scripts that call the same Engine API. PlayCanvas Editor โ†’ [โš›๏ธ Use React](https://developer.playcanvas.com/user-manual/react.md): Describe your scene as JSX components, with hooks for assets, materials, physics and input. PlayCanvas React โ†’ [๐Ÿงฉ Write HTML](https://developer.playcanvas.com/user-manual/web-components.md): Build scenes from tags in a plain web page, with no build step. PlayCanvas Web Components โ†’ ## Explore the Engine The engine's features are documented by topic, and each topic applies whichever way you use the engine. | Topic | What it covers | | --- | --- | | [Entity Component System](https://developer.playcanvas.com/user-manual/ecs.md) | Entities, components and the scene hierarchy | | [Scripting](https://developer.playcanvas.com/user-manual/scripting.md) | Script classes, their lifecycle, attributes and events | | [Assets](https://developer.playcanvas.com/user-manual/assets.md) | Loading and managing models, textures and other files at runtime | | [Graphics](https://developer.playcanvas.com/user-manual/graphics.md) | Cameras, meshes, lighting, materials, shaders, post effects and particles | | [Gaussian Splatting](https://developer.playcanvas.com/user-manual/gaussian-splatting.md) | Rendering, streaming and customizing 3D Gaussian splats | | [Animation](https://developer.playcanvas.com/user-manual/animation.md) | Animation state graphs, layer masks and animation events | | [Physics](https://developer.playcanvas.com/user-manual/physics.md) | Rigid bodies, collision, triggers, ray casts and joints | | [2D](https://developer.playcanvas.com/user-manual/2D.md) | Sprites, 9-slicing, texture atlases and Spine | | [User Interface](https://developer.playcanvas.com/user-manual/user-interface.md) | Screens, layout, text, images and input, on screen or in the 3D world | | [XR](https://developer.playcanvas.com/user-manual/xr.md) | Immersive AR and VR with WebXR, including input and hand tracking | | [Optimization](https://developer.playcanvas.com/user-manual/optimization.md) | Profiling and tuning load time, frame rate and memory | ## In This Section - [Using the Engine Standalone](https://developer.playcanvas.com/user-manual/engine/standalone.md) โ€” set up a project with npm and Vite, or with an import map and a CDN. - [Running the Engine in Node.js](https://developer.playcanvas.com/user-manual/engine/running-in-node.md) โ€” run headless apps for servers, tools and tests. - [Versioning and Releases](https://developer.playcanvas.com/user-manual/engine/versioning.md) โ€” version numbers, npm tags and how to control which updates you get. - [Engine Migrations](https://developer.playcanvas.com/user-manual/engine/migrations.md) โ€” breaking changes and how to update your code. - [Supported Browsers](https://developer.playcanvas.com/user-manual/engine/supported-browsers.md) โ€” minimum browser versions for WebGL 2 and WebGPU. - [Developing with AI](https://developer.playcanvas.com/user-manual/engine/developing-with-ai.md) โ€” set up a coding agent on an Engine project and verify its changes. - [Add-on Libraries](https://developer.playcanvas.com/user-manual/engine/libraries.md) โ€” Spine animation, 3D Tiles streaming, tweening and loaders.gl, used alongside the engine. - [Examples](https://playcanvas.com/examples/) โ€” more than 250 live examples with editable source code. - [API Reference](https://api.playcanvas.com/engine/) โ€” every class, method and property. ## Stay in the Loop - [GitHub](https://github.com/playcanvas/engine) for the source code, issues and pull requests, and [release notes](https://github.com/playcanvas/engine/releases) for every version - [The PlayCanvas blog](https://blog.playcanvas.com/) for Engine news - [Discord](https://discord.gg/RSaMRzg) and the [forum](https://forum.playcanvas.com/) for questions and sharing your work - [The Engine's AI-readable documentation index](https://developer.playcanvas.com/user-manual/engine/llms.txt) for coding agents -------------------------------------------------------------------------------- ## Supported Browsers URL: https://developer.playcanvas.com/user-manual/engine/supported-browsers/ Markdown: https://developer.playcanvas.com/user-manual/engine/supported-browsers.md The PlayCanvas Engine requires a browser with [WebGL 2.0](https://en.wikipedia.org/wiki/WebGL#WebGL_2) support and the JavaScript features described in [Build Target](https://developer.playcanvas.com/user-manual/engine/supported-browsers.md#build-target). The minimum browser versions are: | Browser | Version | Win | macOS | Linux | Chrome OS | Android | iOS | | ------------------------------------------- | ------- | --- | ----- | ----- | --------- | ------- | --- | | [Chrome](https://www.google.com/chrome/) | 80+ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | | [Safari](https://www.apple.com/safari/) | 15+ | | โœ”๏ธ | | | | โœ”๏ธ | | [Firefox](https://www.mozilla.org/firefox/) | 75+ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | | โœ”๏ธ | โœ”๏ธ | | [Edge](https://www.microsoft.com/edge) | 80+ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | | โœ”๏ธ | โœ”๏ธ | | [Opera](https://www.opera.com/) | 67+ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | | โœ”๏ธ | | On iOS and iPadOS, Chrome, Firefox and Edge are built on WebKit, the same browser engine as Safari, so they need iOS or iPadOS 15 or later. Opera for Android numbers its versions separately from desktop Opera, and needs version 57 or later. :::tip We recommend using an up-to-date browser for the best performance and access to newer features like [WebGPU](https://developer.playcanvas.com/user-manual/engine/supported-browsers.md#webgpu). ::: ## WebGPU The Engine renders with WebGL 2.0 by default. An application can request [WebGPU](https://developer.mozilla.org/en-US/docs/Web/API/WebGPU_API) instead when it creates its graphics device with [`createGraphicsDevice`](https://api.playcanvas.com/engine/functions/createGraphicsDevice.html), and the Engine falls back to WebGL 2.0 when WebGPU isn't available. WebGPU is available in: * **Chrome** 113+ on Windows, macOS and ChromeOS, 121+ on Android, and 144+ on Linux with Intel Gen12+ GPUs * **Edge** 113+ on Windows and macOS, and 144+ on Linux with Intel Gen12+ GPUs * **Safari** 26+ on macOS, iOS and iPadOS * **Firefox** 141+ on Windows, and 147+ on macOS with Apple silicon * **Opera** 99+ on Windows and macOS WebGPU support is still expanding, so check [Can I use](https://caniuse.com/webgpu) for the latest coverage. ## Checking Browser Support To verify your browser supports WebGL 2.0, visit [webglreport.com](https://webglreport.com/?v=2). To check for WebGPU, visit [webgpureport.org](https://webgpureport.org/). ๐ŸŽ‰ ## Build Target The PlayCanvas Engine is built targeting ES2020 JavaScript, and its release and profiler ES module builds also use class fields from ES2022. These language features, rather than WebGL 2.0, set the minimum versions of Chrome, Edge, Firefox and Opera above. Older versions of these browsers support WebGL 2.0, but can't run the Engine. -------------------------------------------------------------------------------- ## Using the Engine Standalone URL: https://developer.playcanvas.com/user-manual/engine/standalone/ Markdown: https://developer.playcanvas.com/user-manual/engine/standalone.md It is possible to build applications on the PlayCanvas Engine without using the Editor. Some examples of applications built directly against the Engine are: * [glTF Viewer](https://playcanvas.com/viewer) \[[GitHub](https://github.com/playcanvas/model-viewer)\] * [SuperSplat](https://playcanvas.com/supersplat/editor) \[[GitHub](https://github.com/playcanvas/supersplat)\] * ...and, of course, the [PlayCanvas Editor](https://developer.playcanvas.com/user-manual/editor.md) itself! This page guides you in how to get started. :::note Before you begin, ensure you have [Node.js](https://nodejs.org/) installed. ::: :::tip[Quick start] For a Vite and TypeScript project, use the official [`create-playcanvas`](https://developer.playcanvas.com/user-manual/getting-started/start-with-create-playcanvas.md) tool and choose the Engine format: ```bash npm create playcanvas@latest my-app -- -f engine ``` The generated project includes a runnable starter and [PlayCanvas Skills](https://developer.playcanvas.com/user-manual/getting-started/use-playcanvas-skills.md) for compatible AI coding agents. ::: When setting up your project, there are two main options to consider. ## Option 1: Build Tool and NPM This is the recommended set up that should suit most developers. A build tool can bundle your application into an optimized package that can run on a wide range of browsers. There are many build tools such as [webpack](https://webpack.js.org/), [Rollup](https://rollupjs.org/) and [esbuild](https://esbuild.github.io/), and PlayCanvas will work with all of them. Here, we will use [Vite](https://vitejs.dev/), a popular build tool that aims to provide a faster and leaner development experience for modern web projects. First, select whether you prefer to develop in JavaScript or TypeScript: **JavaScript** 1. Open a Terminal/Command Prompt, create a folder for your app and `cd` inside it. 2. Install `playcanvas` and `vite`: ```sh npm install playcanvas npm install vite --save-dev ``` To control which future Engine releases npm can update to, see [Versioning and Releases](https://developer.playcanvas.com/user-manual/engine/versioning.md). 3. Create an `index.html` and paste this: ```html title="index.html" ``` 4. Create a `main.js` and paste this: ```javascript title="main.js" import { AppBase, AppOptions, CameraComponentSystem, Color, ContainerHandler, createGraphicsDevice, DEVICETYPE_WEBGPU, Entity, FILLMODE_FILL_WINDOW, LightComponentSystem, RenderComponentSystem, RESOLUTION_AUTO, TextureHandler } from 'playcanvas'; // create a graphics device, preferring WebGPU over WebGL 2.0 const canvas = document.getElementById('application'); const device = await createGraphicsDevice(canvas, { deviceTypes: [DEVICETYPE_WEBGPU] }); // create an application with the systems and handlers it uses const options = new AppOptions(); options.graphicsDevice = device; options.componentSystems = [ RenderComponentSystem, CameraComponentSystem, LightComponentSystem ]; options.resourceHandlers = [ TextureHandler, ContainerHandler ]; const app = new AppBase(canvas); app.init(options); app.setCanvasResolution(RESOLUTION_AUTO); app.setCanvasFillMode(FILLMODE_FILL_WINDOW); app.start(); // resize the canvas when the window is resized window.addEventListener('resize', () => app.resizeCanvas()); // create a camera const camera = new Entity(); camera.addComponent('camera', { clearColor: new Color(0.3, 0.3, 0.7) }); camera.setPosition(0, 0, 3); app.root.addChild(camera); // create a light const light = new Entity(); light.addComponent('light'); light.setEulerAngles(45, 45, 0); app.root.addChild(light); // create a box const box = new Entity(); box.addComponent('render', { type: 'box' }); app.root.addChild(box); // rotate the box app.on('update', (dt) => box.rotate(10 * dt, 20 * dt, 30 * dt)); ``` 5. Run the Vite development server: ```sh npx vite ``` This starts a server at `http://localhost:5173`. Visit this URL in your browser and you will see the following: [Image: Spinning Cube] :::tip Every time you save your source files, the tab will reload automatically. ::: **TypeScript** 1. Open a Terminal/Command Prompt, create a folder for your app and `cd` inside it. 2. Install `playcanvas` and `vite`: ```sh npm install playcanvas npm install vite --save-dev ``` To control which future Engine releases npm can update to, see [Versioning and Releases](https://developer.playcanvas.com/user-manual/engine/versioning.md). 3. Create an `index.html` and paste this: ```html title="index.html" ``` 4. Create a `main.ts` and paste this: ```typescript title="main.ts" import { AppBase, AppOptions, CameraComponentSystem, Color, ContainerHandler, createGraphicsDevice, DEVICETYPE_WEBGPU, Entity, FILLMODE_FILL_WINDOW, LightComponentSystem, RenderComponentSystem, RESOLUTION_AUTO, TextureHandler } from 'playcanvas'; // create a graphics device, preferring WebGPU over WebGL 2.0 const canvas = document.getElementById('application') as HTMLCanvasElement; const device = await createGraphicsDevice(canvas, { deviceTypes: [DEVICETYPE_WEBGPU] }); // create an application with the systems and handlers it uses const options = new AppOptions(); options.graphicsDevice = device; options.componentSystems = [ RenderComponentSystem, CameraComponentSystem, LightComponentSystem ]; options.resourceHandlers = [ TextureHandler, ContainerHandler ]; const app = new AppBase(canvas); app.init(options); app.setCanvasResolution(RESOLUTION_AUTO); app.setCanvasFillMode(FILLMODE_FILL_WINDOW); app.start(); // resize the canvas when the window is resized window.addEventListener('resize', () => app.resizeCanvas()); // create a camera const camera = new Entity(); camera.addComponent('camera', { clearColor: new Color(0.3, 0.3, 0.7) }); camera.setPosition(0, 0, 3); app.root.addChild(camera); // create a light const light = new Entity(); light.addComponent('light'); light.setEulerAngles(45, 45, 0); app.root.addChild(light); // create a box const box = new Entity(); box.addComponent('render', { type: 'box' }); app.root.addChild(box); // rotate the box app.on('update', (dt: number) => box.rotate(10 * dt, 20 * dt, 30 * dt)); ``` 5. Run the Vite development server: ```sh npx vite ``` This starts a server at `http://localhost:5173`. Visit this URL in your browser and you will see the following: [Image: Spinning Cube] :::tip Every time you save your source files, the tab will reload automatically. ::: ## Option 2: Import Map and CDN An [import map](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script/type/importmap) can resolve module specifiers in JavaScript modules. Consider this import statement: ```javascript import * as pc from 'playcanvas'; ``` An import map can resolve `playcanvas` to a CDN-hosted build of the engine that can be dynamically loaded by the browser. This means that we can skip the build step described in Option 1. First, select whether you prefer to develop in JavaScript or TypeScript: **JavaScript** 1. Open a Terminal/Command Prompt, create a folder for your app and `cd` inside it. 2. Create an `index.html` and paste this: ```html title="index.html" ``` 3. Create a `main.js` and paste this: ```javascript title="main.js" import { AppBase, AppOptions, CameraComponentSystem, Color, ContainerHandler, createGraphicsDevice, DEVICETYPE_WEBGPU, Entity, FILLMODE_FILL_WINDOW, LightComponentSystem, RenderComponentSystem, RESOLUTION_AUTO, TextureHandler } from 'playcanvas'; // create a graphics device, preferring WebGPU over WebGL 2.0 const canvas = document.getElementById('application'); const device = await createGraphicsDevice(canvas, { deviceTypes: [DEVICETYPE_WEBGPU] }); // create an application with the systems and handlers it uses const options = new AppOptions(); options.graphicsDevice = device; options.componentSystems = [ RenderComponentSystem, CameraComponentSystem, LightComponentSystem ]; options.resourceHandlers = [ TextureHandler, ContainerHandler ]; const app = new AppBase(canvas); app.init(options); app.setCanvasResolution(RESOLUTION_AUTO); app.setCanvasFillMode(FILLMODE_FILL_WINDOW); app.start(); // resize the canvas when the window is resized window.addEventListener('resize', () => app.resizeCanvas()); // create a camera const camera = new Entity(); camera.addComponent('camera', { clearColor: new Color(0.3, 0.3, 0.7) }); camera.setPosition(0, 0, 3); app.root.addChild(camera); // create a light const light = new Entity(); light.addComponent('light'); light.setEulerAngles(45, 45, 0); app.root.addChild(light); // create a box const box = new Entity(); box.addComponent('render', { type: 'box' }); app.root.addChild(box); // rotate the box app.on('update', (dt) => box.rotate(10 * dt, 20 * dt, 30 * dt)); ``` 4. Run `serve`: ```sh npx serve ``` This starts a server at `http://localhost:3000`. Visit this URL in your browser and you will see the following: [Image: Spinning Cube] **TypeScript** 1. Open a Terminal/Command Prompt, create a folder for your app and `cd` inside it. 2. Create an `index.html` and paste this: ```html title="index.html" ``` 3. Create a `main.ts` and paste this: ```typescript title="main.ts" import { AppBase, AppOptions, CameraComponentSystem, Color, ContainerHandler, createGraphicsDevice, DEVICETYPE_WEBGPU, Entity, FILLMODE_FILL_WINDOW, LightComponentSystem, RenderComponentSystem, RESOLUTION_AUTO, TextureHandler } from 'playcanvas'; // create a graphics device, preferring WebGPU over WebGL 2.0 const canvas = document.getElementById('application') as HTMLCanvasElement; const device = await createGraphicsDevice(canvas, { deviceTypes: [DEVICETYPE_WEBGPU] }); // create an application with the systems and handlers it uses const options = new AppOptions(); options.graphicsDevice = device; options.componentSystems = [ RenderComponentSystem, CameraComponentSystem, LightComponentSystem ]; options.resourceHandlers = [ TextureHandler, ContainerHandler ]; const app = new AppBase(canvas); app.init(options); app.setCanvasResolution(RESOLUTION_AUTO); app.setCanvasFillMode(FILLMODE_FILL_WINDOW); app.start(); // resize the canvas when the window is resized window.addEventListener('resize', () => app.resizeCanvas()); // create a camera const camera = new Entity(); camera.addComponent('camera', { clearColor: new Color(0.3, 0.3, 0.7) }); camera.setPosition(0, 0, 3); app.root.addChild(camera); // create a light const light = new Entity(); light.addComponent('light'); light.setEulerAngles(45, 45, 0); app.root.addChild(light); // create a box const box = new Entity(); box.addComponent('render', { type: 'box' }); app.root.addChild(box); // rotate the box app.on('update', (dt: number) => box.rotate(10 * dt, 20 * dt, 30 * dt)); ``` 4. Install `playcanvas` and `typescript`: ```sh npm install playcanvas typescript --save-dev ``` 5. Compile `main.ts` to `main.js`: ```sh npx tsc main.ts --target es2022 --lib esnext,dom --module esnext --moduleResolution bundler --types webxr ``` 6. Run `serve`: ```sh npx serve ``` This starts a server at `http://localhost:3000`. Visit this URL in your browser and you will see the following: [Image: Spinning Cube] ## Configuring the Application The samples create the application in two steps: 1. [`createGraphicsDevice`](https://api.playcanvas.com/engine/functions/createGraphicsDevice.html) creates the graphics device. Listing `DEVICETYPE_WEBGPU` in `deviceTypes` requests WebGPU, and the Engine falls back to WebGL 2.0 when WebGPU isn't available. 2. [`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.html) is initialized with an [`AppOptions`](https://api.playcanvas.com/engine/classes/AppOptions.html) object that lists the component systems and resource handlers the application uses. Because nothing else is registered, a build tool can leave the rest out of your bundle. As your application grows, register what it needs: * **Components**: Each component type needs its component system. For example, add `ScriptComponentSystem` to use the `script` component. [Bundle Size and Tree Shaking](https://developer.playcanvas.com/user-manual/engine/bundle-size.md) lists every component type with its system. If a system is missing, `addComponent` returns `null`, and the debug build of the Engine logs an error. * **Assets**: Each asset type needs its resource handler. The samples register `TextureHandler` for textures and `ContainerHandler` for GLB models. [Bundle Size and Tree Shaking](https://developer.playcanvas.com/user-manual/engine/bundle-size.md#resource-handlers) lists every asset type with its handler. * **Other features**: Sound, batching, lightmapping and XR are enabled with further `AppOptions` properties. For example, the `sound` component also needs `options.soundManager = new SoundManager()`, as [Audio](https://developer.playcanvas.com/user-manual/audio/getting-started.md#setting-up-the-application) describes. :::note The [`Application`](https://api.playcanvas.com/engine/classes/Application.html) class sets all of this up for you. However, its constructor can't create a WebGPU device, it adds every component system and resource handler to your bundle, and it is expected to be deprecated in a future release. ::: -------------------------------------------------------------------------------- ## Bundle Size and Tree Shaking URL: https://developer.playcanvas.com/user-manual/engine/bundle-size/ Markdown: https://developer.playcanvas.com/user-manual/engine/bundle-size.md The PlayCanvas Engine is published on npm as ES modules, one module per source file, and its `package.json` declares `"sideEffects": false`. When you bundle your application with a build tool such as [Vite](https://vite.dev/), [Rollup](https://rollupjs.org/), [esbuild](https://esbuild.github.io/) or [webpack](https://webpack.js.org/), the build tool follows the imports in your code and leaves out every module that nothing uses. This is called tree shaking. Most of what ends up in your bundle is decided by how you set up [`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.html). This page explains how to set it up so that your application includes only what it uses. ## How It Works Your code refers to components and assets by name: `entity.addComponent('render')` or `new Asset('logo', 'texture', { url })`. A build tool can't tell from these strings which parts of the engine your application needs. Instead, `AppBase` registers only the component systems and resource handlers that you list in an [`AppOptions`](https://api.playcanvas.com/engine/classes/AppOptions.html) object: * A **component system** runs one type of component. For example, `RenderComponentSystem` runs the `render` component. * A **resource handler** loads one type of asset. For example, `TextureHandler` loads `texture` assets. Each class you list is imported by your code, so it is included in your bundle. Each class you don't list is left out, together with the code that only it uses. ## Setting Up AppBase This example registers what an application with meshes, a camera, lights, scripts, textures and glTF models needs: ```javascript title="main.js" import { AppBase, AppOptions, CameraComponentSystem, ContainerHandler, createGraphicsDevice, DEVICETYPE_WEBGPU, Keyboard, LightComponentSystem, Mouse, RenderComponentSystem, ScriptComponentSystem, ScriptHandler, TextureHandler, TouchDevice } from 'playcanvas'; const canvas = document.getElementById('application'); const device = await createGraphicsDevice(canvas, { deviceTypes: [DEVICETYPE_WEBGPU] }); const createOptions = new AppOptions(); createOptions.graphicsDevice = device; // input devices the application reads createOptions.mouse = new Mouse(canvas); createOptions.touch = new TouchDevice(canvas); createOptions.keyboard = new Keyboard(window); // component systems and resource handlers the application uses createOptions.componentSystems = [ RenderComponentSystem, CameraComponentSystem, LightComponentSystem, ScriptComponentSystem ]; createOptions.resourceHandlers = [TextureHandler, ContainerHandler, ScriptHandler]; const app = new AppBase(canvas); app.init(createOptions); app.start(); ``` If you use a component without registering its system, `addComponent` returns `null`, and the debug build of the Engine logs `addComponent: System 'sound' doesn't exist`. If you load an asset without registering its handler, the load fails with `No resource handler for asset type`. :::tip During development, Vite and other build tools that set the `development` export condition use the debug build of the Engine, which logs these errors. Production builds use the release build. ::: ## Component Systems Register a component system for each type of component your application adds. The **Also needs** column lists what else the component uses. | Component system | Component | Used for | Also needs | | ---------------- | --------- | -------- | ---------- | | `RenderComponentSystem` | `render` | Meshes, primitive shapes and the entities of glTF models | | | `CameraComponentSystem` | `camera` | Cameras | | | `LightComponentSystem` | `light` | Directional, omni, spot and area lights | | | `ScriptComponentSystem` | `script` | Scripts | `ScriptHandler` to load scripts as `script` assets | | `GSplatComponentSystem` | `gsplat` | Gaussian splats | `GSplatHandler` | | `ParticleSystemComponentSystem` | `particlesystem` | Particle systems | `TextureHandler` for particle textures | | `AnimComponentSystem` | `anim` | Animation state graphs and animation layers | `AnimClipHandler` and `AnimStateGraphHandler` to load `animclip` and `animstategraph` assets | | `AnimationComponentSystem` | `animation` | Legacy animation playback, superseded by `anim` | `AnimationHandler` | | `ModelComponentSystem` | `model` | Legacy meshes, superseded by `render` | `ModelHandler` | | `SoundComponentSystem` | `sound` | Playing sounds | `AudioHandler`, and `soundManager` in `AppOptions` | | `AudioListenerComponentSystem` | `audiolistener` | The listener for positional sound | `soundManager` in `AppOptions` | | `CollisionComponentSystem` | `collision` | Collision shapes and triggers | ammo.js | | `RigidBodyComponentSystem` | `rigidbody` | Rigid body physics | `CollisionComponentSystem`, ammo.js | | `JointComponentSystem` | `joint` | Physics joints | `RigidBodyComponentSystem`, `CollisionComponentSystem`, ammo.js | | `ScreenComponentSystem` | `screen` | The root of a user interface | | | `ElementComponentSystem` | `element` | Text, image and group elements | `ScreenComponentSystem`, `FontHandler` for text, and `elementInput` in `AppOptions` for input | | `ButtonComponentSystem` | `button` | Buttons | `ElementComponentSystem`, `elementInput` in `AppOptions` | | `ScrollViewComponentSystem` | `scrollview` | Scrolling content | `ElementComponentSystem`, `ScrollbarComponentSystem` for its scrollbars | | `ScrollbarComponentSystem` | `scrollbar` | Scrollbars | `ElementComponentSystem` | | `LayoutGroupComponentSystem` | `layoutgroup` | Laying out child elements | `ElementComponentSystem` | | `LayoutChildComponentSystem` | `layoutchild` | Layout settings of an element in a layout group | `ElementComponentSystem`, `LayoutGroupComponentSystem` | | `SpriteComponentSystem` | `sprite` | 2D sprites and sprite animations | `SpriteHandler`, `TextureAtlasHandler` and `TextureHandler` to load sprites | ## Resource Handlers Register a resource handler for each type of asset your application loads. | Resource handler | Asset type | Loads | | ---------------- | ---------- | ----- | | `TextureHandler` | `texture` | Images, HDR images and compressed textures | | `ContainerHandler` | `container` | glTF and GLB models, with their meshes, materials, textures and animations | | `ScriptHandler` | `script` | JavaScript files that define scripts | | `GSplatHandler` | `gsplat` | Gaussian splat files | | `CubemapHandler` | `cubemap` | Cubemaps | | `MaterialHandler` | `material` | Materials stored as JSON | | `RenderHandler` | `render` | Meshes that refer to a `container` asset, as exported by the Editor | | `FontHandler` | `font` | Fonts for text elements | | `AudioHandler` | `audio` | Sound files | | `AnimClipHandler` | `animclip` | Animation clips for the `anim` component | | `AnimStateGraphHandler` | `animstategraph` | Animation state graphs for the `anim` component | | `AnimationHandler` | `animation` | Animations for the legacy `animation` component | | `ModelHandler` | `model` | Models for the legacy `model` component | | `SpriteHandler` | `sprite` | Sprites | | `TextureAtlasHandler` | `textureatlas` | Texture atlases for sprites | | `SceneHandler` | `scene` | Scenes exported by the Editor | | `JsonHandler` | `json` | JSON data | | `TextHandler` | `text` | Text files | | `BinaryHandler` | `binary` | Binary data, as an `ArrayBuffer` | ## Other Options The other properties of `AppOptions` add features in the same way: what you don't set is not included. | Option | Value | Used for | | ------ | ----- | -------- | | `graphicsDevice` | A `GraphicsDevice`, from `createGraphicsDevice` | Rendering. Required. | | `mouse` | `new Mouse(canvas)` | Reading mouse input through `app.mouse` | | `touch` | `new TouchDevice(canvas)` | Reading touch input through `app.touch` | | `keyboard` | `new Keyboard(window)` | Reading keyboard input through `app.keyboard` | | `gamepads` | `new GamePads()` | Reading gamepad input through `app.gamepads` | | `elementInput` | `new ElementInput(canvas)` | Mouse and touch input on user interface elements | | `soundManager` | `new SoundManager()` | Playing sounds with the `sound` and `audiolistener` components | | `lightmapper` | The `Lightmapper` class | Baking lightmaps at runtime | | `batchManager` | The `BatchManager` class | Combining mesh instances into batches | | `xr` | The `XrManager` class | WebXR, through `app.xr` | | `assetPrefix` | A string | A prefix added to the URL of every asset | | `scriptPrefix` | A string | A prefix added to the URL of every script | | `scriptsOrder` | An array of script URLs | The order in which scripts are loaded | | `devtools` | `true` or `false` | Whether the application announces itself to developer tools such as the PlayCanvas Inspector. Defaults to `true`. | Each input device stays `null` on the application unless you set it here. ## Keeping the Bundle Small * **Import from `playcanvas`.** The package name resolves to the per-module build that build tools can tree shake. The single-file builds in `playcanvas/build/` are meant for use without a build tool, such as from an import map. * **Use the engine's exports directly.** Named imports (`import { Entity } from 'playcanvas'`) and members of a namespace import (`pc.Entity`) both tree shake. Passing the whole namespace to a function as a value, as in `setup(pc)`, makes some build tools, such as esbuild, keep the entire engine. * **Check what your bundle contains.** esbuild prints the size of each module with `--analyze`, and [rollup-plugin-visualizer](https://github.com/btd/rollup-plugin-visualizer) draws a map of a Vite or Rollup bundle. -------------------------------------------------------------------------------- ## Running the Engine in Node.js URL: https://developer.playcanvas.com/user-manual/engine/running-in-node/ Markdown: https://developer.playcanvas.com/user-manual/engine/running-in-node.md [Node.js](https://nodejs.org/) is a cross-platform, open-source JavaScript runtime environment that can run on Windows, Linux, macOS, and more. It runs on the V8 JavaScript engine, and executes JavaScript code outside a web browser. Node.js lets developers use JavaScript to write command line tools and for server-side scripting. The PlayCanvas Engine fully supports running in Node.js. This can be useful for: * creating multiplayer servers * creating tools for processing asset data * writing unit tests for your application :::note The PlayCanvas Engine runs its own [unit tests](https://github.com/playcanvas/engine/blob/main/test/README.md) using Node.js. ::: ## Installation Before you begin, verify you have Node.js 18+ installed. Then you can install the PlayCanvas Engine using npm. ```bash npm install playcanvas ``` ## Creating a Headless Application When running a PlayCanvas application in Node.js, you are unlikely to require rendering. In this case, you can create a [`NullGraphicsDevice`](https://api.playcanvas.com/engine/classes/NullGraphicsDevice.html), which renders nothing. Since there is nothing to display, a plain object can stand in for the canvas. ```javascript import { AppBase, AppOptions, NullGraphicsDevice, ScriptComponentSystem } from 'playcanvas'; // Nothing is rendered, so a plain object stands in for the canvas const canvas = { width: 1, height: 1 }; const options = new AppOptions(); options.graphicsDevice = new NullGraphicsDevice(canvas); options.componentSystems = [ScriptComponentSystem]; const app = new AppBase(canvas); app.init(options); app.start(); ``` [`AppBase`](https://api.playcanvas.com/engine/classes/AppBase.html) only runs the component systems that you register. This application registers the script component system, which [Adding Scripts](https://developer.playcanvas.com/user-manual/engine/running-in-node.md#adding-scripts) uses. Register a system for each other component type you add, as described in [Configuring the Application](https://developer.playcanvas.com/user-manual/engine/standalone.md#configuring-the-application). ## Updating the Application In a browser, `app.start()` begins a main loop driven by `requestAnimationFrame`. Node.js has no `requestAnimationFrame`, so no main loop runs. Instead, call [`app.update(dt)`](https://api.playcanvas.com/engine/classes/AppBase.html#update) at the rate you need. This updates the component systems you registered, such as scripts, animation or physics, and skips rendering entirely. ```javascript const TICK_RATE = 20; // updates per second setInterval(() => { app.update(1 / TICK_RATE); }, 1000 / TICK_RATE); ``` Passing a fixed `dt` gives every update the same length, however much the timer drifts. ## Adding Scripts [ESM scripts](https://developer.playcanvas.com/user-manual/scripting/esm-scripts.md) are standard JavaScript modules, so Node.js can import them directly. For example, here is a script that rotates its entity: ```javascript title="rotate.mjs" import { Script } from 'playcanvas'; export class Rotate extends Script { static scriptName = 'rotate'; update(dt) { this.entity.rotate(0, 90 * dt, 0); } } ``` Import the script class and pass it to the script component: ```javascript import { Entity } from 'playcanvas'; import { Rotate } from './rotate.mjs'; const entity = new Entity('Box'); entity.addComponent('script'); entity.script.create(Rotate); app.root.addChild(entity); ``` The script's `update` method now runs every time you call `app.update(dt)`. ## Using jsdom Some parts of the engine rely on DOM APIs that Node.js does not provide: * classic scripts, which are loaded with a ` ``` In your application **ESM** ```javascript import { Application } from 'playcanvas'; window.addEventListener("message", (event) => { if (event.origin === "http://example.com") { // always check message came from your website const score = event.data.score; // call API method one: window.setScore(score); // call API method two: const app = Application.getApplication(); app.fire("score:set", score); } }, false); ``` **Classic** ```javascript window.addEventListener("message", function (event) { if (event.origin === "http://example.com") { // always check message came from your website const score = event.data.score; // call API method one: window.setScore(score); // call API method two: const app = pc.Application.getApplication(); app.fire("score:set", score); } }, false); ``` ### Serve your own HTML When you download your PlayCanvas application for self-hosting. This is the index.html page that we include to run your application. ```html Application Title ``` It is absolutely possible and even recommended, that you start from this page as the basis of your web page and you can modify it to add any additional content that is required for your page. When it comes to communicating with your PlayCanvas application, for example from a button push. You can call the APIs we defined above directly from your script. There is no need for the `postMessage` calls. Note, it is important that you run any custom code after the `__start__.js` scripts as this creates the PlayCanvas application. In many cases you may wish to wait until after all the asset loading has finished, but before the application starts. You can do this by responding to the `start` event. For example: ```html Application Title ``` -------------------------------------------------------------------------------- ## Hosting using a CDN URL: https://developer.playcanvas.com/user-manual/editor/publishing/web/hosting-cdn/ Markdown: https://developer.playcanvas.com/user-manual/editor/publishing/web/hosting-cdn.md When deploying your PlayCanvas application for self-hosting it is often necessary to separate the location your application is served from (the index.html) from the assets that the application loads. For example, a Content Delivery Network (CDN) is used to make sure that assets are delivered from a server that is geographically close to the user's computer. This makes your application load much more quickly. This guide will show you how to configure your PlayCanvas application to use a separate location for your assets. The first step is to download a web build of your application following the steps in [the publishing guide](https://developer.playcanvas.com/user-manual/editor/publishing/web/self-hosting.md). Then we start by making changes to the `index.html` and `__settings__.js` files in the downloaded build. ## Serving Assets from another location The simplest change to make is to load all assets from a different location. This is done by setting the `ASSET_PREFIX` property in your `__settings__.js`. [Image: settings.js] The `ASSET_PREFIX` will be prepended to all request that are made for an asset (including a scene) both during the preload phase and during runtime. For example, you should set this to the root folder of your CDN asset store. In the above example, previously an asset that would have had a URL like `files/123456/1/texture.jpg` will now be loaded from `http://keepy-up-cdn.example.com/files/123456/1/texture.jpg`. ## Additional URLs There are a few remaining files that are referenced directly by the `index.html`. In particular, the style sheet, the PlayCanvas javascript engine, the `__settings__.js`, `__loading__.js` and `__start__.js` application scripts. Update your index.html as seen below. [Image: index.html] In `__settings__.js`, the path to the application settings `config.json` would need to be changed as well. Update [Image: settings.js] ## Copy Files to CDN Next you should copy all the required files into the new location on your server. These files are loaded using the `ASSET_PREFIX`: `__game_scripts.js`, scene json (e.g. `123456.json`), `config.json`, assets (everything inside the `files` folder) and `logo.png` the default loading screen logo. And these files are referenced by the index.html: - `playcanvas-stable.min.js`, - `manifest.json` - `__settings__.js` - `__loading__.js` - `__start__.js` - `styles.css` [Image: CDN files] You should copy all these files onto your CDN hosting service. ## Setting up CORS Your application is now ready to load files from a separate server. The final step to tackle is to ensure your server is correctly set up to serve Cross-Origin Resource Sharing (CORS) headers. CORS is a security feature of the browser which means that by default a web page on `http://example.com` can't download files from a web page on `http://keepy-up-cdn.example.com/` because they have a different "origin". To get around this, you must set the server at `http://keepy-up-cdn.example.com/` to serve CORS headers that tell the browser that other pages are allowed to download the content. Setting up CORS is different depending on which CDN or server you are using. You will need to check the documentation of your server or CDN provider to find out how to set up CORS header. For example, the page for Amazon Web Services CORS settings is [here](https://docs.aws.amazon.com/AmazonS3/latest/userguide/cors.html) -------------------------------------------------------------------------------- ## Hosting on heyVR.io URL: https://developer.playcanvas.com/user-manual/editor/publishing/web/hosting-heyvr/ Markdown: https://developer.playcanvas.com/user-manual/editor/publishing/web/hosting-heyvr.md [heyVR.io](https://heyvr.io) is a publishing platform for WebXR games, giving you access to a global audience of hundreds of thousands of players across multiple devices. It offers a wide range of ready-to-use gameplay features to enhance your players' experience and enable you to start earning from your game through in-game content sales and advertisements. ## Publishing Flow To publish your game on heyVR, you'll need to follow a few simple steps: 1. Create a developer account (assuming you don't have one yet) 2. Upload your game 3. Publish! You can optionally integrate the [heyVR SDK](https://docs.heyvr.io/en/game-development/sdk) into your game, which will boost player engagement and grant you access to useful features such as leaderboards, cloud saves, matchmaking and more. ### 1. Create a developer account Simply head over to the heyVR's [developer area](https://developer.heyvr.io) and register your developer account free of charge. After registration, you'll be able to create/manage your games. To read more, check out the [documentation](https://docs.heyvr.io). ### 2. Upload your game Once you have created your developer account, you'll need to download a web build of your application. The steps for this process are explained in detail on the [Self-hosting](https://developer.playcanvas.com/user-manual/editor/publishing/web/self-hosting.md#self-hosting-on-your-own-server) documentation page. Simply follow the steps for **Self-hosting on your own server** to acquire a **zip** file. Once you have the zip build, you can follow the step-by-step guide on [publishing a game](https://docs.heyvr.io/en/developer-area/publish-a-game) on heyVR. The guide includes all the steps, requirements and common questions regarding the publishing process. ### 3. Publish That's it! By now you should be able to see, view and test your game on heyVR. Once you're ready to make it publicly accessible, you can submit your game for review. The review process is to ensure that your game aligns with the [Publishing Guidelines](https://heyvr.io/hc/legal/heyvr-io-publishing-policies) and is fully functional. ### 4. SDK Implementation (optional) To further enrich the user experience and boost engagement to your game, you can use the [heyVR SDK](https://docs.heyvr.io/en/game-development/sdk) to implement additional features in your game. The SDK offers the following features and more: - User Management - Leaderboards - Cloud Saves - In-Game Purchases (both free & paid) - In-Game Advertisements - Multiplayer A comprehensive guide on how to implement these features into your game is provided on heyVR's [Technical Documentation](https://docs.heyvr.io/en/game-development/sdk). ## Useful Links - [Developer Area](https://developer.heyvr.io) - [heyVR Documentation](https://docs.heyvr.io) - [heyVR Support (Discord)](https://heyvr.io/discord) -------------------------------------------------------------------------------- ## Mobile URL: https://developer.playcanvas.com/user-manual/editor/publishing/mobile/ Markdown: https://developer.playcanvas.com/user-manual/editor/publishing/mobile.md PlayCanvas games are just web pages. An index.html file and a collection of resources (JavaScript files, JSON files, images and so on). They work great in web browsers, of course, but if you want to submit your game to a mobile app store such as Google Play or the Apple App Store, then you somehow need to convert your PlayCanvas game to a native app. There are a few products available to simplify the process for you: * [Cordova](https://developer.playcanvas.com/user-manual/editor/publishing/mobile/cordova.md) * [GoNative](https://developer.playcanvas.com/user-manual/editor/publishing/mobile/gonative.md) Alternatively, another option is to create an Android or iOS app that consists of a single fullscreen WebView that loads your PlayCanvas app from local app resources. -------------------------------------------------------------------------------- ## Apache Cordova URL: https://developer.playcanvas.com/user-manual/editor/publishing/mobile/cordova/ Markdown: https://developer.playcanvas.com/user-manual/editor/publishing/mobile/cordova.md [Apache Cordova](https://cordova.apache.org/) is an open-source mobile development framework. It allows you to use standard web technologies - HTML5, CSS3, and JavaScript for cross-platform development. Applications execute within wrappers targeted to each platform, and rely on standards-compliant API bindings to access each device's capabilities such as sensors, data, network status, etc. You can use Cordova to natively wrap your PlayCanvas app. You can then publish it to the iOS App Store and Android's Google Play. Cordova can also generate executables compatible with macOS and Windows. ## Installing Cordova To get started, follow the [instructions](https://cordova.apache.org/docs/en/latest/guide/cli/index.html#installing-the-cordova-cli) for installing Cordova on your computer. ## Creating a Project To create a project, issue the following command: ```sh cordova create hello com.example.hello HelloWorld ``` `hello` is the folder in which the project is created. `com.example.hello` is the reverse domain-style identifier for your app. `HelloWorld` is the human readable title of your app (it is the name of the generated app icon, for example). So, for a game like [Master Archer](https://playcanv.as/p/JERg21J8/), an appropriate command would be: ```sh cordova create masterarcher com.playcanvas.masterarcher "Master Archer" ``` Once your project is created, you will find a file called `config.xml` in the project's root folder. Here you can configure or edit certain characteristics of your app. For example, you can optionally [set up custom icons](https://cordova.apache.org/docs/en/latest/config_ref/images.html) for your app, either globally or per-platform. ## Adding your PlayCanvas App When you create a new Cordova project, it generates a skeleton web app in a folder called `www`. You can go ahead and delete everything in the `www` folder. Next, copy your PlayCanvas app files to this location. If you're building on the Engine without the Editor, copy your app files into `www` such that your `index.html` file is in the root. :::note Audio asset files will need to be in Base64 format to load and play correctly. This is due to iOS being restrictive about what files can be loaded in the WebView via local disk. We recommend using a tool like [Base64 Guru](https://base64.guru/converter/encode/audio) or automating this via a script. ::: If you have built your app in the PlayCanvas Editor, we have an official external tool that will build and prepare the project to be most compatible with Cordova. This includes automating tasks such as converting the audio files to Base64 so that they can be loaded on iOS. The official external tool can be found on GitHub [here](https://github.com/playcanvas/playcanvas-rest-api-tools#cordova-publish). Follow the [setup steps](https://github.com/playcanvas/playcanvas-rest-api-tools#setup) from the readme in the GitHub repo. And run the command for the [Cordova Publish script](https://github.com/playcanvas/playcanvas-rest-api-tools#cordova-publish) as shown in the readme. This will create a ZIP of the project ready for Cordova. Extract its contents to the root of the `www` folder. ## Building Executables You are now ready to build your app for any of the platforms supported by Cordova. ### Building for iOS Building for iOS is limited to macOS based computers. You must also ensure you have Xcode installed. You can install it from the [Mac App Store](https://apps.apple.com/us/app/xcode/id497799835?mt=12). To build your app for iOS, add the Cordova iOS platform to your project. From the root of your project, issue the command: ```sh cordova platform add ios ``` Ensure that the version is `6.0.0` or higher. This is because version `6.0.0` upgraded the wrapper to use WKWebView instead of UIWebView, which brings better performance. Read more on [Cordova's blog](https://cordova.apache.org/announcements/2020/06/01/cordova-ios-release-6.0.0.html). By default, if you attempt to run a Cordova-based PlayCanvas app, you will encounter several errors/exceptions related to cross-origin HTTP requests. To fix this, add the following to your project's `config.xml`: ```html ``` ### Testing for iOS You are now ready to test your app. For iOS, you can use Simulator or run on a physical iOS device. Simulator is installed as part of the Xcode tools, runs on your Mac and simulates the various iOS based devices. To run your app in Simulator, issue the following command: ```sh cordova run ios ``` Once the executable has been generated in the build process, Simulator will start and load it. You should see something like the following: [Image: Master Archer in Simulator] To run on a physical device: 1. Connect your iOS device to your Mac via USB. 2. Open `platforms/ios/.xcworkspace` in Xcode. 3. Navigate to the Signing & Capabilities settings for your project's Target and select a valid Team so that your app can be digitally signed before being deployed to your device. 4. Select your iOS device in Xcode's Scheme drop-down list. [Image: Xcode Scheme drop-down] 5. Press the Run button to build, deploy and run the application on your device. [Image: Xcode Run button] Once you are happy with your app, you can ship it to [App Store Connect](https://developer.apple.com/app-store-connect/). -------------------------------------------------------------------------------- ## GoNative URL: https://developer.playcanvas.com/user-manual/editor/publishing/mobile/gonative/ Markdown: https://developer.playcanvas.com/user-manual/editor/publishing/mobile/gonative.md [GoNative](https://gonative.io/) is a paid third party service that can take a URL and create a native mobile application that uses a native WebView to run on mobile in a few clicks. As it is using a WebView, the user has to be online to use the app and you will have to host your PlayCanvas application somewhere such as [AWS Web Hosting services](https://aws.amazon.com/websites/). GoNative also provides simple integration of mobile native plugins that can be accessed from your PlayCanvas application such as Google AdMob and In-App Purchases. A full list of [plugins can be found here](https://gonative.io/plugins). -------------------------------------------------------------------------------- ## Desktop URL: https://developer.playcanvas.com/user-manual/editor/publishing/desktop/ Markdown: https://developer.playcanvas.com/user-manual/editor/publishing/desktop.md It is possible to convert your PlayCanvas app to a native executable for each of the major desktop operating systems: Windows, Mac OS X and Linux. To do this, we recommend using [NW.js](https://nwjs.io/). Instructions for generating the executable can be found on the [NW.js Wiki](https://github.com/nwjs/nw.js/wiki/How-to-package-and-distribute-your-apps). -------------------------------------------------------------------------------- ## Playable Ads URL: https://developer.playcanvas.com/user-manual/editor/publishing/playable-ads/ Markdown: https://developer.playcanvas.com/user-manual/editor/publishing/playable-ads.md We are currently supporting the following playable ad networks: * [Facebook](https://developer.playcanvas.com/user-manual/editor/publishing/playable-ads/fb-playable-ads.md) * [Snapchat](https://developer.playcanvas.com/user-manual/editor/publishing/playable-ads/snapchat-playable-ads.md) Other ad networks may be supported but have not yet been tested by the PlayCanvas team. -------------------------------------------------------------------------------- ## Facebook Playable Ad URL: https://developer.playcanvas.com/user-manual/editor/publishing/playable-ads/fb-playable-ads/ Markdown: https://developer.playcanvas.com/user-manual/editor/publishing/playable-ads/fb-playable-ads.md PlayCanvas supports the [Facebook Playable Ad](https://www.facebook.com/business/ads/playable-ad-format) formats and requirements via an [official external tool on GitHub](https://github.com/playcanvas/playcanvas-rest-api-tools). [Image: Facebook Playable Ads] The tool can create both the single 2MB (uncompressed) HTML file and the 5MB (uncompressed) ZIP formats via the configuration options. Full specifications for Facebook Playable Ads can be found on their [help center](https://www.facebook.com/business/help/412951382532338). ## Example project The [Cube Jump project](https://playcanvas.com/project/354998/overview/cube-jump-playable-ad-for-fb) is ready to be exported for the Facebook Playable Ad format and the expected [HTML output can be found here](https://developer.playcanvas.com/downloads/fb-playable-ad-cube-jump-html.zip). [Interactive demo: Cube Jump Playable Ad](https://playcanv.as/e/p/Hywjl9Bh/) ## File size tips As there is a strict file size limit, you will have to plan and budget the usage of assets for the ad. The minified PlayCanvas Engine code is **\~1.2MB** uncompressed and due to the need to encode the asset files into Base64 strings, it adds **\~30%** to the size of each asset file. This means that for a single HTML format, this leaves \~500KB for assets before they are encoded into Base64 strings. For the ZIP format, this would be about \~3MB for assets before encoding. Try to keep images as small as possible in dimensions and use tools like [TinyPNG](https://tinypng.com/) to reduce file size even further. ## Playable ad checklist * Have you added the function call `FbPlayableAd.onCTAClick()` as part of your call to action callback? ## How to export Follow the [setup steps](https://github.com/playcanvas/playcanvas-rest-api-tools#setup) from the readme in the GitHub repo. ### Single HTML Set the following options in the `config.json` as shown below. This will produce a single HTML file in the output directory. ```json "one_page": { "patch_xhr_out": true, "inline_game_scripts": true, "extern_files": false } ``` ### ZIP file Set the following options in the `config.json` as shown below. This will produce a ZIP file with the asset data and PlayCanvas Engine code as separate files from the `index.html`. ```json "one_page": { "patch_xhr_out": true, "inline_game_scripts": true, "extern_files": true } ``` And run the command: ```sh npm run one-page ``` Full details of options and commands can be found in the readme section for '[Converting a project into a single HTML file](https://github.com/playcanvas/playcanvas-rest-api-tools#converting-a-project-into-a-single-html-file)'. ### How to test Follow the steps [here](https://www.facebook.com/business/help/338940216641734) to create a Facebook ad and at the time where the files for the ad are uploaded, there is an opportunity to test within the manager. [Image: Test Ad] Please ignore the warning about the source may contain an `XMLHttpRequest` as the code path has been removed by this tool. Facebook also allows testing on device via the ad manager but requires you to publish the ad first. This is a strange limitation by Facebook but is required at the moment. [Image: Preview Ad] -------------------------------------------------------------------------------- ## Snapchat Playable Ad URL: https://developer.playcanvas.com/user-manual/editor/publishing/playable-ads/snapchat-playable-ads/ Markdown: https://developer.playcanvas.com/user-manual/editor/publishing/playable-ads/snapchat-playable-ads.md PlayCanvas supports the Snapchat Playable Ad format and requirements via an [official external tool on GitHub](https://github.com/playcanvas/playcanvas-rest-api-tools#converting-a-project-into-a-single-html-file). Snapchat playable ads uses the [MRAID 2.0 API](https://www.iab.com/guidelines/mraid/) standard and requires the assets for the ad to be external from the `index.html` rather than embedded. The external assets will need to be in a folder that is uniquely named (which the tool handles for you) so that they can be uploaded to Snapchat's CDN servers. There are some limitations to be aware of with the tool which can be found in the documentation from [GitHub](https://github.com/playcanvas/playcanvas-rest-api-tools#converting-a-project-into-a-single-html-file). ## Example project The [Cube Jump project](https://playcanvas.com/project/796932/overview/cube-jump-snapchat-ad) is ready to be exported to the Snapchat Playable Ad format and the expected HTML output can be found [here](https://developer.playcanvas.com/downloads/sc-playable-ad-cube-jump.zip). [Interactive demo: Cube Jump Playable Ad](https://playcanv.as/e/p/X1nwbUGA/) ## File size tips As there is a soft limit of 5MB (uncompressed), you will have to plan and budget the usage of assets for the ad. The minified PlayCanvas Engine code is **\~1.2MB** uncompressed and due to the need to encode the asset files into Base64 strings, it adds **\~30%** to the size of each asset file. This means that you would have about \~3MB for assets before the Base64 encoding. Try to keep images as small as possible in dimensions and use tools like [TinyPNG](https://tinypng.com/) to reduce file size even further. ## Playable ad checklist The Snapchat ad network requires the call to action function to be in the `index.html` where the network can replace it with a unique tracking version when it is served to the user. The URL will be set in the Snapchat Ad campaign tool. The tool wraps this logic in a global function: `snapchatCta();` that should be called in the playable ad project. * Have you called the function `snapchatCta();` as part of the call to action callback? ## How to export Follow the [setup steps](https://github.com/playcanvas/playcanvas-rest-api-tools#setup) from the readme in the GitHub repo. ### Dry run test As Snapchat does not yet have an official tool to test with, we will have to do a dry run to test with first before exporting in a format that the Snapchat ad network expects. Set the following options in the `config.json` as shown below. This will produce a ZIP file with the asset data and PlayCanvas Engine code as separate files from the `index.html`. ```json "one_page": { "patch_xhr_out": false, "inline_game_scripts": true, "extern_files": { "enabled": true, "folder_name": "78fb9255-3033-4fe2-b9e1-355b149229a1", "external_url_prefix": "" }, "mraid_support": true, "snapchat_cta": true } ``` The `folder_name` needs to be a unique string. For this purpose, you can use a random GUID from a [GUID generator](https://www.guidgenerator.com/) or your Snapchat representative may have a specific string that you should use. And run the command: ```sh npm run one-page ``` Full details of options and commands can be found in the readme section for '[Converting a project into a single HTML file](https://github.com/playcanvas/playcanvas-rest-api-tools#converting-a-project-into-a-single-html-file)'. To test the ad on a device, we can use the Android app [Creative Preview](https://play.google.com/store/apps/details?id=com.google.android.apps.audition&hl=en_GB&gl=US) but we need to host the ad on a https server. Our recommended approach is to [host locally](https://developer.playcanvas.com/user-manual/editor/publishing/web/self-hosting.md#running-a-downloaded-build) and use [ngrok](https://ngrok.com/) to create a https tunnel to your computer that the app can access. Once this is setup, open Creative Preview app and create a new 'Display' ad with the following settings: ### Export for Snapchat When the ad is ready to be uploaded for Snapchat, we need to add Snapchat's CDN URL prefix to the asset references in `index.html`. We can do this via the options in `config.json` via the `external_url_prefix` property: ```json "one_page": { "patch_xhr_out": false, "inline_game_scripts": true, "extern_files": { "enabled": true, "folder_name": "78fb9255-3033-4fe2-b9e1-355b149229a1", "external_url_prefix": "https://rtb-ads.shadow.snapads.com/html5" }, "mraid_support": true, "snapchat_cta": true } ``` The ZIP can then be given to your Snapchat representative to upload to the ad network. -------------------------------------------------------------------------------- ## Snapchat Web Lenses URL: https://developer.playcanvas.com/user-manual/editor/publishing/snapchat-web-lenses/ Markdown: https://developer.playcanvas.com/user-manual/editor/publishing/snapchat-web-lenses.md A [Snapchat Web Lens](https://developers.snap.com/web-lenses/home) is a web app that runs inside Snapchat as a Lens, full screen and in portrait, on iOS and Android. This page explains how to publish an Editor project as one. For a code project, start from the [Snapchat Web Lens starter](https://developer.playcanvas.com/user-manual/getting-started/start-with-create-playcanvas.md#snapchat-web-lens-starter) instead. Before you publish, check your game against Snap's [Platform requirements](https://developers.snap.com/web-lenses/requirements) and [Capabilities and restrictions](https://developers.snap.com/web-lenses/capabilities). In particular, a Lens runs in portrait and can load files only from its own zip, so your project must not load anything from another host. ## Add the Web Lens API The [Web Lens API](https://developers.snap.com/web-lenses/web-lens-api) gives your game leaderboards, the player's Bitmoji, and storage that lasts between launches. To add it to your project: 1. Download `snap-api.js` from the `dist` folder of the [`@snap/web-lens-api`](https://www.npmjs.com/package/@snap/web-lens-api) package. 2. Upload it to your project as a script asset. 3. In the asset's Inspector, set **Loading Type** to **Before Engine**. The script installs the API as `window.snapchat`, so your scripts can call `snapchat.init()` at startup and check `snapchat.isSupported()` before using each capability. The API must ship inside your zip, so do not add it under **Settings > External Scripts**. Outside Snapchat, including on the Launch page, the API answers from a built-in stub with canned data. ## Download and Zip the Build 1. [Download a build](https://developer.playcanvas.com/user-manual/editor/publishing/web/self-hosting.md) of your project from the **Publish** dialog. 2. Zip the *contents* of the build folder, so that `index.html` sits at the root of the zip rather than inside a folder. On Windows, avoid PowerShell's `Compress-Archive`, which writes backslashes into the zip that break relative paths. 3. Check the zip with `unzip -l`. It must be no more than 8 MB, and `index.html` no more than 1 MB. ## Upload to Snapchat Sign in to [My Lenses](https://my-lenses.snapchat.com/), create a new Lens, choose the Web Lens option, and upload your zip. Snap's [Publishing](https://developers.snap.com/web-lenses/publishing) guide covers the details you add, such as the icon and the preview video, and the review process. -------------------------------------------------------------------------------- ## Editor API URL: https://developer.playcanvas.com/user-manual/editor/editor-api/ Markdown: https://developer.playcanvas.com/user-manual/editor/editor-api.md :::warning The Editor API is a beta feature. Please use caution when using on live projects. ::: The Editor has a user accessible API that is currently in beta which can be used to help automate and extend the base functionality. The API is not yet considered stable and may change in the future as we continue development. However, it is unlikely that API will change a lot from its current state. The Editor API is open sourced on [GitHub](https://github.com/playcanvas/editor-api). The API documentation can be found [here](https://api.playcanvas.com/editor/). ## Automation Example The API can be accessed via the browser's devtools console allowing for automation of repetitive tasks. In the example below, we are using the Editor to find all the Entities that have the tag 'red' and disabling them by running code in the browser console. Editor API code: ```javascript (function() { const entities = editor.api.globals.entities.root.listByTag('red'); for (const entity of entities) { entity.set('enabled', false); } })(); ``` ## Extending Editor Functionality It is possible to add extra functionality to the Editor and create custom interfaces such as adding buttons. This can be done via a number of ways such as browser extensions or [user scripts](https://en.wikipedia.org/wiki/Userscript). User scripts is the more accessible out of the two which allows you to run custom code on top of the Editor. Below we have an example where a button has been added to the [Viewport](https://developer.playcanvas.com/user-manual/editor/interface/viewport.md) to generate and randomly place boxes into the scene. The PlayCanvas team are currently using the [Violentmonkey](https://violentmonkey.github.io/) open source browser extension to manage user scripts. Once the browser extension has been installed, adding your own or another developer's user script is very straightforward. Steps can be found in [Violentmonkey's documentation](https://violentmonkey.github.io/guide/creating-a-userscript/). The code for the above user script is: ```javascript // ==UserScript== // @name Example Script // @namespace Violentmonkey Scripts // @match https://playcanvas.com/editor/scene/* // @grant none // @version 1.0 // @author - // @description 20/10/2021, 11:40:21 // ==/UserScript== (function() { async function generateBoxes(count, position, radius) { // create box entity const box = editor.api.globals.entities.create({ parent: editor.api.globals.entities.root }); // find box material asset const boxMaterial = editor.api.globals.assets.findOne(asset => asset.get('name') === 'boxMaterial'); // add render component box.addComponent('render', { type: 'box', materialAssets: [boxMaterial.get('id')] }); // add a number of boxes around a point in the scene let offset = new pc.Vec3(); let rotation = new pc.Quat(); const result = []; for (let i = 0; i < count; i++) { const boxCopy = await box.duplicate(); boxCopy.set('name', 'Box ' + (i + 1)); offset.set(1, 0, 0); rotation.setFromEulerAngles(0, pc.math.random(-360, 360), 0); offset = rotation.transformVector(offset); offset.scale(pc.math.random(-radius, radius)); boxCopy.set('position', [position.x + offset.x, position.y + offset.y, position.z + offset.z]); result.push(boxCopy); } // delete original box box.delete(); return result; } function createButton() { const btn = new pcui.Button({ text: 'Generate Boxes' }); btn.style.position = 'absolute'; btn.style.bottom = '10px'; btn.style.right = '10px'; editor.call('layout.viewport').append(btn); let boxes; btn.on('click', () => { // delete existing boxes if (boxes) { editor.api.globals.entities.delete(boxes); boxes = null; } generateBoxes(10, new pc.Vec3(), 10).then(result => { boxes = result; }); }); } // Wait until the Editor is available before adding the button editor.once('load', () => createButton()); })(); ``` Let's break down the important areas of the script: At the top is the informational header about the script if you do share the script with other users. The important line is the `@match` attribute which controls which URLs the script is loaded on. In this case, it is set to load on any PlayCanvas scene. More information on how to change this can be found in [Violentmonkey's documentation](https://violentmonkey.github.io/api/matching/). ```javascript // ==UserScript== // @name Example Script // @namespace Violentmonkey Scripts // @match https://playcanvas.com/editor/scene/* // @grant none // @version 1.0 // @author - // @description 20/10/2021, 11:40:21 // ==/UserScript== ``` This is private Editor API to wait for an event when the Editor has fully loaded. Using the event ensures that the Editor API is accessible before the code to extend Editor features is run. ```javascript // Wait until the Editor is available before adding the button editor.once('load', () => createButton()); ``` The button created is from the [PCUI](https://github.com/playcanvas/pcui) framework library that the Editor is also using. Again, there is some private API use to get the Viewport DOM to attach the button to. ```javascript function createButton() { const btn = new pcui.Button({ text: 'Generate Boxes' }); btn.style.position = 'absolute'; btn.style.bottom = '10px'; btn.style.right = '10px'; editor.call('layout.viewport').append(btn); let boxes; btn.on('click', () => { // delete existing boxes if (boxes) { editor.api.globals.entities.delete(boxes); boxes = null; } generateBoxes(10, new pc.Vec3(), 10).then(result => { boxes = result; }); }); } ``` -------------------------------------------------------------------------------- ## MCP Server URL: https://developer.playcanvas.com/user-manual/editor/mcp-server/ Markdown: https://developer.playcanvas.com/user-manual/editor/mcp-server.md The [PlayCanvas Editor MCP Server](https://github.com/playcanvas/editor-mcp-server) connects AI assistants to an open PlayCanvas Editor session. It can modify project data and verify the result through the viewport or a running application. Your MCP client starts the local server, and the Editor connects to it. Almost every tool acts on the project currently open in that Editor. A small set of [project tools](https://developer.playcanvas.com/user-manual/editor/mcp-server.md#manage-projects) can also list, create, update and open the projects of the signed-in account, so the assistant can work from the Project Dashboard before any project is open. ## Install the Server Once Install [Node.js 22.18 or later](https://nodejs.org/) before configuring your MCP client. The commands use the published [`@playcanvas/editor-mcp-server`](https://www.npmjs.com/package/@playcanvas/editor-mcp-server) package through `npx`. ### Claude Code ```bash claude mcp add playcanvas -- npx -y @playcanvas/editor-mcp-server ``` ### Codex ```bash codex mcp add playcanvas -- npx -y @playcanvas/editor-mcp-server ``` On Windows, run: ```bash codex mcp add playcanvas -- cmd /c npx -y @playcanvas/editor-mcp-server ``` ### Cursor and Claude Desktop Add this server to the client's MCP configuration: ```json { "mcpServers": { "playcanvas": { "command": "npx", "args": ["-y", "@playcanvas/editor-mcp-server"] } } } ``` In Cursor, open **Settings > Cursor Settings > MCP**. In Claude Desktop, open **Settings > Developer > Edit Config**. Restart the client after changing its configuration. :::note Windows For JSON-based clients on Windows, use `"command": "cmd"` and prepend `"/c"` to the `args` array. ::: ## Connect the Project 1. Open a project in the PlayCanvas Editor. 2. Select the **MCP** button at the bottom of the Editor toolbar. 3. Check that the port is `52000` and select **Connect**. [Image: Editor MCP Server connection panel] Keep the MCP client running while you use the connection. Only one Editor instance can connect to the server at a time, so disconnect another Editor before changing projects or browser tabs. :::note Browser Permission Chromium browsers ask before letting a website reach a server running on your own machine (Chrome 142 and later; Chrome 147 extends this to the connection the Editor uses). Select **Allow** when prompted, or open the padlock menu in the address bar and allow **Apps on device**. Only the Editor needs this permission โ€” the Launch page is bridged through it. A blocked connection fails silently and looks the same as a server that is not running. ::: To use another port, append `--port ` to the server arguments and enter the same port in the Editor. ### Connect from the Project Dashboard The [Project Dashboard](https://developer.playcanvas.com/user-manual/editor/projects/dashboard.md) at [playcanvas.com/editor](https://playcanvas.com/editor) has an **MCP server** button in the account row at the bottom of the sidebar. Select it to open the **MCP server** panel, which shows the **Status** and **Port**, and select **Connect**. [Image: MCP Server] The connection is remembered. When the tab moves into a project, whether you open it or the assistant does, the Editor reconnects on load without another click. ## Manage Projects With the Project Dashboard or a project connected, the assistant can manage the projects of the signed-in account: | Tool | What it does | | --- | --- | | `list_projects` | Lists your projects, or an organization's, with their ids. | | `get_project` | Reads one project's summary. With no id, it reads the project open in the Editor. | | `create_project` | Creates a project. Set `open` to open it once it is ready. | | `update_project` | Changes a project's name, description or visibility. | | `open_project` | Opens a project in the connected tab. The tab reloads into the project and the Editor reconnects. | Only `name`, `description`, `private` and `owner` (a username) can be set. Any other field is rejected by name. Plan limits apply, so a private project needs a paid plan. On the Project Dashboard no project is open, so the scene and asset tools report that until the assistant opens one. [Video](https://developer.playcanvas.com/video/editor-mcp-projects.mp4) ```text List my PlayCanvas projects. Create a project called "Cube Garden", open it, and add a ring of ten colourful cubes around the box in its scene. ``` :::note The project tools need a version of the [Editor MCP Server](https://github.com/playcanvas/editor-mcp-server) newer than 0.7.1, and Editor 2.35 or later. ::: ## Check the Connection Without Editing Begin with a read-only request. This confirms that the assistant can see the intended Editor and gives it context before any mutation. ```text Inspect the project currently connected through PlayCanvas MCP. Report the loaded scene, current selection, and version-control status. Do not change anything. ``` If the assistant reports the wrong scene or project, connect the correct Editor tab before continuing. ## Create a Recovery Point MCP operations change the Editor project directly; there is no local Push step. Create a checkpoint before a substantial task. ```text Check the current version-control status. If the project is ready for changes, create a checkpoint named "Before lighting update". Do not switch branches, reset state, or modify the scene yet. ``` If other collaborators have unsaved work or the project is not in the expected state, resolve that before asking the assistant to continue. ## Describe the Change and Its Proof Give the assistant one observable result rather than a list of tool calls. Include the scene or assets in scope, constraints it must preserve, and how it should prove completion. ```text In the loaded scene, improve the lighting around the vehicle display without moving the vehicle or camera. Reuse the existing lights where possible. When finished, capture the Editor viewport, launch the scene, capture the running result, and report any console errors. ``` The assistant can inspect and edit entities, components, scripts, assets, scenes, project settings, templates, animation data, builds, and version-control state. Let it select the tools needed for the requested outcome. ## Verify the Running Result For scene or behavior changes, source inspection is not enough. Ask the assistant to: 1. Capture the Editor viewport to check composition and selected objects. 2. Start a Launch instance. 3. Capture the running application. 4. Read runtime logs and query relevant entity state. 5. Inject keyboard, mouse, or touch input when interaction is part of the task. 6. Stop the Launch instance when verification is complete. Allow pop-ups for the PlayCanvas Editor origin so the server can open the Launch window. It uses your existing PlayCanvas login session. Starting a Launch instance when one is already running attaches to it rather than restarting it, so a session in progress is not thrown away; ask for a specific option, such as a graphics device, to force a fresh launch. This demo shows an assistant auditing a legacy Engine V1 project, cross-referencing the PlayCanvas documentation, migrating it to Engine V2 and ESM Scripts with checkpoints, and verifying the running result. [Video](https://developer.playcanvas.com/video/editor-mcp-legacy-migration.mp4) ## Review or Recover Ask the assistant to summarize what it changed and the evidence it observed. Inspect the scene yourself before accepting the result. - Use Editor undo/redo for a recent isolated edit. - Restore the checkpoint when the entire task should be abandoned. - Create a new checkpoint after accepting a substantial result. Do not ask the assistant to hard-reset, delete a branch, restore a checkpoint, or delete project data unless you intend that destructive operation. ## When to Use the VS Code Extension Instead Use the [VS Code Extension workflow](https://developer.playcanvas.com/user-manual/editor/scripting/vscode-extension.md) when the assistant only needs to edit text-based assets and you want to review filesystem diffs before pushing anything to PlayCanvas. Use MCP when the task needs direct Editor, scene, asset, viewport, or runtime access. ## Troubleshooting ### The Editor Does Not Connect Confirm that the MCP client is running the server, the client and Editor both use the same port, and no other Editor is connected. Restart the MCP client after changing its configuration. If the panel stays on **Connecting** and reports that the browser blocked the connection, open the padlock menu for the Editor and allow **Apps on device**. ### The First Connection Times Out The first `npx` run may need time to download the package. Start the client again after the download finishes. Codex users can also increase `startup_timeout_sec` under `[mcp_servers.playcanvas]` in `~/.codex/config.toml`. ### Launch Does Not Open Allow pop-ups for the Editor origin, close an existing Launch window, and ask the assistant to start the Launch instance again. ### The Launch Instance Never Connects The Launch window opens but the runtime tools report that it did not connect. Reload the Editor so it picks up the current build, then start the Launch instance again. ### The Assistant Is Operating on the Wrong Project MCP tools always target the project open in the connected Editor. Ask the assistant to open the intended project with `open_project`, or disconnect, open it yourself and reconnect before making more changes. :::caution The server acts through your current Editor session and can perform destructive operations such as deleting entities, assets, builds, or branches and resetting project state. Review these operations before allowing them and create a checkpoint before substantial changes. ::: -------------------------------------------------------------------------------- ## Engine Compatibility URL: https://developer.playcanvas.com/user-manual/editor/engine-compatibility/ Markdown: https://developer.playcanvas.com/user-manual/editor/engine-compatibility.md ## Introduction The Editor supports two major release streams of the engine: - The latest release of engine v1.x.x (**Engine V1**) - This supports WebGL1 and WebGL2, and receives critical bug fixes. It does not receive any new features. - The latest release of engine v2.x.x (**Engine V2**) - This supports WebGL2 and WebGPU but not WebGL1 for rendering. It receives both new features and fixes. You are free to switch between these at any time. ### Switching projects between Engine V1 and V2 This process will involve migration and updating of scripts given differences in our Engine API between Engine V1 and V2. All details regarding the engine changes can be found [here](https://developer.playcanvas.com/user-manual/engine/migrations.md) To initiate this navigate to the settings panel and click the `SWITCH TO ENGINE V2` button to convert your project to using Engine V2 (This will require a confirmation before converting). If you wish to switch back, there is a `SWITCH TO ENGINE V1` button in the same location for Project V2. :::important It is recommended to create a checkpoint before switching engines. ::: :::warning Once the switch has been confirmed, **all users** in the current project will be reloaded. ::: #### Scripting Given the changes in API for the engine you may wish to test your project in the launcher with Engine V1 or V2. You can do this by enabling the Force Engine V2 or Force Engine V1 checkboxes in the launcher options: Additionally, conditionally checking the Engine version at runtime will allow your script to be made compatible with both versions of the engine during the transition time. :::ai When behavior differs between Engine versions, use the **[Editor MCP Server](https://developer.playcanvas.com/user-manual/editor/mcp-server.md)** to reproduce the same scenario in each. An AI assistant can correlate logs and captures with affected scripts and APIs to suggest a focused fix. ::: #### Gamma and Tonemap These settings were previously found under the rendering section of the Settings panel. However, in Engine V2, these have been moved to be set per camera. Each camera component will now have these additional fields: The viewport settings are now located inside the EDITOR section of the Settings panel: :::note If you change the settings per camera and switch back to Project V1, your per-camera settings will be lost. ::: #### sRGB Textures For Engine V2, textures must be set as sRGB or not, depending on their use case. The textures that store color data, such as diffuse and emissive maps, should use sRGB for accurate color representation. This is found under the texture asset panel as shown above. These will be automatically set. However, if there are conflicts, the console will display them: Click on the console message to open up the conflicting reference. If you wish to use the same texture for both sRGB and not, it is advised to duplicate your texture to cover both cases. -------------------------------------------------------------------------------- ## Common Questions URL: https://developer.playcanvas.com/user-manual/editor/faq/ Markdown: https://developer.playcanvas.com/user-manual/editor/faq.md ## How do I add a component? To add a **component** to an Entity, select the Entity and then click **Add Component** in the **Inspector** or right click on the Entity and select a component from the Add Component context menu. [Learn more](https://developer.playcanvas.com/user-manual/editor/scenes/components.md) ## How do I add a script? You can use JavaScript to control the behavior of entities. Select any entity, add a script component and create a new script asset. [Learn more](https://developer.playcanvas.com/user-manual/editor/scripting/managing-scripts.md) ## How do I change the background color? To change the background color of your scene, you should update the Clear Color property of the camera in your scene. You could also try adding a [skybox](https://developer.playcanvas.com/user-manual/editor/assets/inspectors/cubemap.md) to your scene. [Learn more](https://developer.playcanvas.com/user-manual/editor/scenes/components/camera.md) ## How do I change the material of a model? Every surface on a 3D model is rendered using a **material**. The material defines the properties of that surface, such as its color, shininess, bumpiness etc. You can create a new material and drag and drop it on your model or you can select its existing materials and edit their properties in the Inspector. [Learn more](https://developer.playcanvas.com/user-manual/editor/assets/inspectors/material.md) ## How do I create a cubemap? Cubemaps are a special type of texture asset. They are formed from 6 texture assets where each texture represents the face of a cube. To create a cubemap click on the **Add** button in the Assets panel and select **New Cubemap**. Then drag 6 textures in the cubemap inspector. To take advantage of Physically Based Rendering make sure you click **Prefilter** after setting the 6 textures. [Learn more](https://developer.playcanvas.com/user-manual/editor/assets/inspectors/cubemap.md) ## How do I create an Entity? You can create a new Entity by clicking on the Add button in the Hierarchy panel or right click on an Entity and use the **New Entity** menu item. ## How do I create a light? You can create a light by adding a **Light** component to an Entity. You can also right click on an Entity and select New Entity / Directional Light to create a new directional light and similarly for spot lights and omni lights. [Learn more](https://developer.playcanvas.com/user-manual/editor/scenes/components/light.md) ## How do I create a material? Every surface on a 3D model is rendered using a **material**. The material defines the properties of that surface, such as its color, shininess, bumpiness etc. To create a material click on the **Add** button in the Assets panel and then select **New Material**. [Learn more](https://developer.playcanvas.com/user-manual/editor/assets/inspectors/material.md) ## How do I create a new shader? You can create a new shader asset from the asset panel. Click **Add Asset -> Shader**. [View tutorial](http://developer.playcanvas.com/tutorials/custom-shaders/) ## How do I create a shape like a box or sphere? You can add primitive shapes like boxes, spheres and others by adding a **Render Component** on an Entity and changing its type to the desired shape. You can also right click on an Entity and select New Entity/Box to add a box (similarly for other shapes). [Learn more](https://developer.playcanvas.com/user-manual/editor/scenes/components/render.md) ## How do I create a skybox? To create a skybox for your scene you first need to create a [Cubemap asset](https://developer.playcanvas.com/user-manual/editor/assets/inspectors/cubemap.md). Then you can drag and drop the Cubemap inside the 3D viewport, or you can go to the Scene Settings and drag the Cubemap in the Skybox field. [Learn more](https://developer.playcanvas.com/user-manual/editor/interface/settings/rendering.md) ## How do I delete an asset? To delete an asset select it and press **Delete** or right click on it and select Delete. ## How do I delete an Entity? You can delete an Entity by selecting it and pressing **Delete**. Alternatively you can click on the Delete button in the Hierarchy panel or right click on the Entity and select Delete from the context menu. ## How do I duplicate an Entity? To duplicate an Entity use the Duplicate button in the Hierarchy panel or press **Ctrl+D**. You can also copy and paste an Entity. To copy press **Ctrl+C** and to paste **Ctrl+V**. ## How do I play an animation? To play an animation of a 3D model you need to create an Entity with a [Model Component](https://developer.playcanvas.com/user-manual/editor/scenes/components/model.md) and an [Animation Component](https://developer.playcanvas.com/user-manual/editor/scenes/components/animation.md). The **Model Component** will render your model and the **Animation Component** will play animations. To render the model drag a model Asset in the Asset field of the Model Component. To play animations drag Animation Assets on the Assets field of the Animation Component. ## How do I play a sound? To play sounds you need to add a [Sound component](https://developer.playcanvas.com/user-manual/editor/scenes/components/sound.md) to an Entity. Then you can create slots to play [Audio assets](https://developer.playcanvas.com/user-manual/editor/assets/inspectors/audio.md). Simply click "Add Slot" and drag an Audio Asset on the Asset field. In order to hear the sounds you also need to add an [AudioListener component](https://developer.playcanvas.com/user-manual/editor/scenes/components/audiolistener.md) to an Entity - usually to the Camera Entity. You can create Audio assets by dragging audio files from your computer into the Assets panel. [View tutorial](https://developer.playcanvas.com/tutorials/basic-audio/) ## How do I remove a component? To remove a component, select the Entity and then click on the **Delete** button in the Inspector next the componentโ€™s title. ## How do I render a 3D model? To render a 3D model you need to add a **Model Component** to an Entity and drag a **Model Asset** on the Asset field. Alternatively you can drag and drop a Model Asset from the Assets Panel into the 3D Viewport. [Learn more](https://developer.playcanvas.com/user-manual/editor/scenes/components/model.md) ## How do I move / rotate / scale an Entity? To move an Entity, select it and then move it using the **Translate tool**. To rotate it use the **Rotate tool** and to scale it use the **Scale tool**. Switch between the Translate / Rotate / Scale tools by pressing 1 / 2 / 3 respectively. ## How do I upload assets? To upload Assets simply drag and drop files from your computer into the Assets panel. Your files will be processed by the server and will appear shortly after in the Assets Panel. [Learn more](https://developer.playcanvas.com/user-manual/editor/assets/importing.md) ## How do I use physics? To give physical properties to an Entity you need to add a [Collision component](https://developer.playcanvas.com/user-manual/editor/scenes/components/collision.md) to it and a [RigidBody component](https://developer.playcanvas.com/user-manual/editor/scenes/components/rigidbody.md). The Collision component gives a physical shape to the Entity and the RigidBody component makes the Entity be simulated by the physics engine. You can change the default [gravity](https://developer.playcanvas.com/user-manual/editor/interface/settings/physics.md) in the Scene Settings. [View tutorial](https://developer.playcanvas.com/tutorials/collision-and-triggers/) ## How do I use real-time shadows? Real-time shadows are rendered for each light source that has **Cast Shadows** enabled. To enable shadows, select an Entity with a Light component and enable Cast Shadows. You also need to enable Cast Shadows on any Model components in your scene. [Learn more](https://developer.playcanvas.com/user-manual/graphics/lighting/shadows.md) -------------------------------------------------------------------------------- ## Troubleshooting URL: https://developer.playcanvas.com/user-manual/editor/troubleshooting/ Markdown: https://developer.playcanvas.com/user-manual/editor/troubleshooting.md This is a list compiled of all the most commonly asked questions and answers for the Editor powered by Engine V2 for projects running Engine V1 or V2. ## 1. My scene looks brighter/darker in the Editor when it was powered by Engine V1 vs V2 ### Check Camera settings - Check **gamma** and **tone mapping** for scene under **Settings -> Rendering** - Check **gamma** and **tone mapping** for viewport under **Settings -> Editor** - Check **gamma** and **tone mapping** for each `CameraComponent` (**Engine V2 PROJECT ONLY**) #### Scene Settings #### Viewport Settings #### Camera Settings ### Check Texture sRGB flags - Check if you have any audit fixes **Status Bar -> N audits found** - Fixes can be applied automatically **Status Bar -> N audits found -> Fix Issues** - Conflicts have to be resolved case-by-case: 1. Refer to **Console Output** for which textures/texture atlases are affected and where they are used 2. Click each warning/error to jump to where the texture/sprite is used #### Asset Auditor [Video](https://developer.playcanvas.com/video/asset-auditor.mp4) ## 2. My camera makes objects look brighter/darker in the Editor compared to the Launcher If the camera is created by a script, make sure the **gamma** and **tone mapping** settings are explicitly set on the camera component. -------------------------------------------------------------------------------- ## PlayCanvas React URL: https://developer.playcanvas.com/user-manual/react/ Markdown: https://developer.playcanvas.com/user-manual/react.md [@playcanvas/react](https://github.com/playcanvas/react) brings PlayCanvas to the React ecosystem. It provides a declarative, component-based approach to building interactive 3D applications using familiar React patterns and a powerful ECS architecture. It's a thin wrapper around PlayCanvas - a batteries-included library for building interactive 3D content in React. [Getting Started โ†’](https://developer.playcanvas.com/user-manual/react/getting-started.md) [View on GitHub โ†—](https://github.com/playcanvas/react) ## How does it Work? PlayCanvas has a powerful ECS architecture that aligns perfectly with React's declarative nature. You create Entities, add Components to them, and load assets. That's it. No more worrying about the underlying engine, just build your scene. Here's how you load and render a 3D model and create an orbit camera. ```tsx export const Lambo = () => { // Load an asset const { asset: model } = useModel('/assets/lambo.glb'); // If the asset is not loaded, return null if (!model) return null; return <> {/* create and position a camera entity */} {/* Add a camera component */} {/* Add an orbit controls component */} {/* render the asset */} } ``` ## Full Engine Power, React Simplicity PlayCanvas React gives you access to the **entire** PlayCanvas Engine - no third-party libraries required. If it's possible in PlayCanvas, it's possible in PlayCanvas React. On top of that, PlayCanvas React adds a set of **React-first features** to make development faster and more ergonomic: - **Asset Loading** โ€“ React-style asset loading with Suspense. Fine-grained control over when and how assets are fetched. - **Pointer Events** โ€“ Familiar event bubbling for clicks, drags and gestures. Attach listeners to any entity and handle events naturally. - **Physics** โ€“ Lazy-loaded physics engine that integrates cleanly with React's lifecycle. - **Hooks** โ€“ Convenient hooks for engine events, materials, asset state and more. ## Getting Started Follow our [Getting Started](https://developer.playcanvas.com/user-manual/react/getting-started.md) guide which will walk you through your first PlayCanvas React project. Alternatively, you can spin up a new project in seconds with our [StackBlitz template](https://playcanvas-react.vercel.app/new) ## Examples But less talking, more doing. Here are a couple of examples you can try with PlayCanvas React: [Physics Example](https://developer.playcanvas.com/user-manual/react/examples/physics.md): Physics Disturb rigid bodies in zero gravity. [Clock Example](https://stackblitz.com/edit/pc-react-tick-tock?file=src%2FScene.tsx): Clock Open a simple PlayCanvas React template in StackBlitz. ## Learn More - [Getting Started Guide](https://developer.playcanvas.com/user-manual/react/getting-started.md) - Set up your first project - [Building a Scene](https://developer.playcanvas.com/user-manual/react/building-a-scene.md) - Learn the fundamentals of scene composition - [Features Showcase](https://playcanvas-react.vercel.app/docs#features) - Explore all capabilities - [Interactive Playground](https://playcanvas-react.vercel.app/examples) - Learn by doing - [API Reference](https://playcanvas-react.vercel.app/docs/api) - Complete component documentation Explore the [official documentation](https://playcanvas-react.vercel.app/docs) or browse the [GitHub repository](https://github.com/playcanvas/react) for more. -------------------------------------------------------------------------------- ## Getting Started URL: https://developer.playcanvas.com/user-manual/react/getting-started/ Markdown: https://developer.playcanvas.com/user-manual/react/getting-started.md Welcome to PlayCanvas React! This section will guide you through setting up your first 3D React application and teach you the fundamental concepts you need to build interactive 3D experiences. ## What You'll Learn In this getting started guide, you'll learn how to: - [Install and set up](https://developer.playcanvas.com/user-manual/react/getting-started/installation.md) PlayCanvas React in your project - [Create your first 3D scene](https://developer.playcanvas.com/user-manual/react/building-a-scene.md) with cameras, entities, and 3D models - [Load and manage 3D assets](https://developer.playcanvas.com/user-manual/react/guide/loading-assets.md) efficiently in your application ## Prerequisites Before you begin, make sure you have: - **Node.js** 22.23.2 or later installed on your system - Basic familiarity with **React** - if you're new to React, check out the [React documentation](https://react.dev/learn) - A text editor or IDE (we recommend [Visual Studio Code](https://code.visualstudio.com/)) ## Quick Start The fastest way to get started is with [`create-playcanvas`](https://developer.playcanvas.com/user-manual/getting-started/start-with-create-playcanvas.md): ```bash npm create playcanvas@latest my-app -- -f react ``` Choose one of the runnable starters when prompted. The generated project includes [PlayCanvas Skills](https://developer.playcanvas.com/user-manual/getting-started/use-playcanvas-skills.md) for compatible AI coding agents. You can also try our [online playground](https://playcanvas-react.vercel.app/new) without installing anything locally. ## Next Steps Ready to dive in? Start with the [installation guide](https://developer.playcanvas.com/user-manual/react/getting-started/installation.md) to set up your development environment, then follow the [building a scene](https://developer.playcanvas.com/user-manual/react/building-a-scene.md) tutorial to build your first 3D application. For more advanced topics and examples, explore the complete [PlayCanvas React documentation](https://playcanvas-react.vercel.app/docs) and [example gallery](https://playcanvas-react.vercel.app/examples). -------------------------------------------------------------------------------- ## Installation URL: https://developer.playcanvas.com/user-manual/react/getting-started/installation/ Markdown: https://developer.playcanvas.com/user-manual/react/getting-started/installation.md The recommended way to get started is to use the official [`create-playcanvas`](https://developer.playcanvas.com/user-manual/getting-started/start-with-create-playcanvas.md) scaffolding tool and choose the React format: ```bash npm create playcanvas@latest my-app -- -f react ``` Choose one of the runnable starters when prompted. The generated TypeScript project includes Vite, development and production scripts, and [PlayCanvas Skills](https://developer.playcanvas.com/user-manual/getting-started/use-playcanvas-skills.md) for compatible AI coding agents. We recommend following [this guide](https://developer.playcanvas.com/user-manual/react/building-a-scene.md) to start building your first project. ## Manual Installation If you have an existing project, just install `@playcanvas/react` using your preferred package manager. **npm** ```bash npm install @playcanvas/react playcanvas ``` **yarn** ```bash yarn add @playcanvas/react playcanvas ``` **pnpm** ```bash pnpm add @playcanvas/react playcanvas ``` Once installed, you can start using it in your project. As the next step, we recommend following the [building a scene guide](https://developer.playcanvas.com/user-manual/react/building-a-scene.md) to create your first project. ### Starter Templates Explore the complete [starter catalogue](https://developer.playcanvas.com/user-manual/getting-started/start-with-create-playcanvas.md#choose-a-starter), or quickly spin up a project from the [StackBlitz template](https://stackblitz.com/edit/playcanvas-react-template?file=src%2FScene.tsx). -------------------------------------------------------------------------------- ## Building a Scene URL: https://developer.playcanvas.com/user-manual/react/building-a-scene/ Markdown: https://developer.playcanvas.com/user-manual/react/building-a-scene.md This guide will walk you through the process of setting up a new `@playcanvas/react` project and creating a simple 3D scene. By the end of this guide, you'll have a basic understanding of the core concepts of PlayCanvas React. At the end you'll have something like the following. An interactive 3D scene built with @playcanvas/react. :::info This guide assumes you have some familiarity with React. If you're new to React, it's worth taking a look at the [React documentation](https://react.dev/learn) to get up to speed. ::: We'll build the scene step by step, and you'll see the code and live examples at each step. ## Your first scene If you've not already done so, **follow the [Installation Guide](https://developer.playcanvas.com/user-manual/react/getting-started/installation.md)**, and create a new PlayCanvas React project. ```bash npm create playcanvas@latest my-first-3d-app -- -f react ``` Before we get to anything more complex, let's create a simple example that displays a box. Any PlayCanvas scene starts with an **Application**, a **Scene** and a **Camera** so we can see something. In your `/src/App.tsx` file, you can delete everything and replace it with the following code. **Rendering a simple box** ```jsx title="/src/App.tsx" import { Application, Entity } from '@playcanvas/react' import { Render, Camera } from '@playcanvas/react/components' const Scene = () => { return (<> ) } export const App = () => ( ) ``` When you run this or click the Demo tab, you'll see a square in the center of the screen. ### What's happening here? We've created a PlayCanvas `Application` and a separate `Scene` that contains an `Entity` with a `Render` component. The `Application` is the root of every PlayCanvas application. It sets up an HTML `canvas` element and defines a rendering context. We've abstracted out a `Scene` that contains everything we want to render. It's not strictly necessary, but it's a clean and logical way to organize your code. Inside the `Scene`, we've added an `Entity` component with a `Render` component. The `Entity` component is simply a container. It can be positioned, rotated and scaled, but on its own, it doesn't do anything. The `Render` component gives the `Entity` the ability to render 3D assets. :::tip PlayCanvas uses an **ECS architecture**. You add **'components'** to an `Entity` to give it functionality. ::: Finally we've added a `Camera` component to the `Entity`. When you attach a `Camera` component to an `Entity`, it will render the scene from that entity's position down the entity's negative Z axis. We've set the camera's position to `[0, 0, 5]` so that it's a bit away from the box. If you play with those values, you'll see how it changes the rendered scene. ## Adding lights This is a great start, but we don't have any lights in the scene. You can add lighting to the scene by either adding an `Environment` or `Light` component. There are various types of lights in PlayCanvas, so check the [docs](https://developer.playcanvas.com/user-manual/graphics/lighting/lights.md) for a broader overview. For now, we'll use environmental lighting (which provides a more naturally lit scene) and a simple directional light which we'll use later to help ground the scene. **Adding lights to the scene** ```jsx title="/src/App.tsx" import { Application, Entity } from '@playcanvas/react' import { Render, Camera, Light, Environment } from '@playcanvas/react/components' import { useEnvAtlas } from '@playcanvas/react/hooks' const Scene = () => { // load the assets const { asset: envAtlas } = useEnvAtlas('/assets/environment.png'); // if the asset hasn't loaded, don't render anything if (!envAtlas) return null; return (<> ) } export const App = () => ( ) ``` If you run this or click the Demo tab, you'll see the box with a bit of lighting. There are a few new concepts here, so let's break them down. ### Loading assets We've loaded an environment atlas using the `useEnvAtlas` hook. This is a hook that allows us to load an environment atlas from a URL which we pass to the `Environment` component. The library provides a number of powerful hooks for loading different types of assets that let you manage loading states and errors. [Learn more](https://developer.playcanvas.com/user-manual/react/guide/loading-assets.md) about loading assets. ### Adding components - `Environment` - This component adds environmental lighting to the scene. - `Light` - This component adds a light to the scene. - `Render` - This component renders the box. We do this by loading an environment atlas and passing it to the `Environment` component, and adding a `Light` component. ## Adding interactivity Ok, so we have some lighting. Let's add some interactivity by adding a `Script` component so you can rotate the cube with the mouse. We'll use the `CameraControls` script to allow the camera to be rotated with the mouse. We've also added a `Camera` component to the `Entity` to set the clear color and field of view. **Adding interactivity to the scene** ```jsx title="/src/App.tsx" import { Application, Entity } from '@playcanvas/react' import { Render, Camera, Light, Environment } from '@playcanvas/react/components' import { useEnvAtlas } from '@playcanvas/react/hooks' import { Script } from '@playcanvas/react/components' import { CameraControls } from 'playcanvas/scripts/esm/camera-controls.mjs' const Scene = () => { // load the assets const { asset: envAtlas } = useEnvAtlas('/assets/environment.png'); // if the asset hasn't loaded, don't render anything if (!envAtlas) return null; return (<> ) } export const App = () => ( // highlight-next-line ``` You can then import the Web Components as follows: ```html ``` :::note[Versioning] The snippets above use `@latest` for convenience. For production deployments, pin to a specific version to ensure deterministic builds (for example: `playcanvas@2.x.y` and `@playcanvas/web-components@x.y.z`). Choose a pair that works together: each release of `@playcanvas/web-components` supports a range of engine versions, declared as the `playcanvas` peer dependency in its `package.json`. The library's URL appears twice, in the import map and in the ` ``` These paths assume your site is served from the project root, so that `/node_modules/...` resolves. ## Your First Page Here is a complete page that renders a lit sphere โ€” the "hello, world" of 3D. It uses the CDN setup, so there is nothing to install: ```html title="index.html" {29-41} My PlayCanvas Web Components App ``` One rule in the ` ``` ## Templates in the Examples Several of the library's examples are built on this pattern, in increasing order of ambition: * [Physics Cluster](https://playcanvas.github.io/web-components/examples/#physics-cluster.html) โ€” the minimal case: forty spheres cloned from one template into a gravity well, using `importNode()`. * [UI Layout](https://playcanvas.github.io/web-components/examples/#ui-layout.html) โ€” tiles cloned into a [``](https://developer.playcanvas.com/user-manual/web-components/tags/pc-layout-group.md), which lays out each new arrival automatically. * [Scroll View](https://playcanvas.github.io/web-components/examples/#scroll-view.html) โ€” list entries cloned into scrollable content and removed by their own buttons. * [AR Wiener Storm](https://playcanvas.github.io/web-components/examples/#ar-wiener-storm.html) โ€” the full treatment: a jointed, physics-driven [``](https://developer.playcanvas.com/user-manual/web-components/tags/pc-model.md) prefab whose bare-name references wire each clone internally, with readiness raced against teardown. -------------------------------------------------------------------------------- ## XR Support URL: https://developer.playcanvas.com/user-manual/web-components/xr/ Markdown: https://developer.playcanvas.com/user-manual/web-components/xr.md PlayCanvas Web Components make it easy to add Virtual Reality (VR) and Augmented Reality (AR) support to your applications. ## Basic Setup To enable XR support, you'll need: 1. A `` rendering with WebGL 2 (see below). 2. XR-specific scripts (provided by the [Engine NPM package](https://www.npmjs.com/package/playcanvas)). 3. A camera rig with the XR scripts attached. 4. UI for entering XR (WebXR requires a user gesture to start a session). 5. A secure context โ€” serve your page over HTTPS (or `http://localhost` during development). `` renders with WebGPU by default, but the engine can only host an XR session on WebGPU where the browser exposes `XRGPUBinding`, the bridge between WebXR and WebGPU. Where it does not (Chrome, for one, at the time of writing), the engine reports XR as unavailable. So give any page that offers XR a WebGL 2 backend: ```html ``` A page embedded in an ` ``` ## Phones and Tablets A tap unlocks audio in the same way as a click. One more thing catches people out on iPhones: by default, Web Audio is silent while the phone's ring/silent switch is set to silent, as if it were a ringtone. If your players report that an app has no sound on an iPhone, this is the first thing to ask about. Where Safari supports the [Audio Session API](https://developer.mozilla.org/en-US/docs/Web/API/AudioSession), an app can ask to be treated as media playback, which plays whatever the switch is set to: ```javascript if (navigator.audioSession) { navigator.audioSession.type = 'playback'; } ``` ## Example This Engine app plays music from a slot with Auto Play, behind a start screen that shows whenever audio is locked. The status line shows the state of the audio context and the position of the music. If you have already clicked on this page, audio is unlocked, and the music starts as soon as the example loads. Click **Lock audio** to suspend the audio context and see the locked state. ```js live-example import { AppBase, AppOptions, Asset, AudioHandler, CameraComponentSystem, Color, createGraphicsDevice, DEVICETYPE_WEBGPU, Entity, FILLMODE_FILL_WINDOW, LightComponentSystem, RenderComponentSystem, RESOLUTION_AUTO, SoundComponentSystem, SoundManager, StandardMaterial } from 'playcanvas'; // create the application with the component systems and resource handlers it uses const canvas = document.getElementById('application'); const device = await createGraphicsDevice(canvas, { deviceTypes: [DEVICETYPE_WEBGPU] }); device.maxPixelRatio = Math.min(window.devicePixelRatio, 2); const options = new AppOptions(); options.graphicsDevice = device; options.soundManager = new SoundManager(); options.componentSystems = [ RenderComponentSystem, CameraComponentSystem, LightComponentSystem, SoundComponentSystem ]; options.resourceHandlers = [AudioHandler]; const app = new AppBase(canvas); app.init(options); app.setCanvasFillMode(FILLMODE_FILL_WINDOW); app.setCanvasResolution(RESOLUTION_AUTO); window.addEventListener('resize', () => app.resizeCanvas()); app.start(); app.scene.ambientLight = new Color(0.35, 0.35, 0.4); const asset = new Asset('music', 'audio', { url: 'https://developer.playcanvas.com/assets/music.mp3' }); await new Promise((resolve) => { asset.ready(resolve); app.assets.add(asset); app.assets.load(asset); }); const camera = new Entity('camera'); camera.addComponent('camera', { clearColor: new Color(0.11, 0.12, 0.17) }); camera.setPosition(0, 0, 4); app.root.addChild(camera); const light = new Entity('light'); light.addComponent('light'); light.setEulerAngles(48, 38, 0); app.root.addChild(light); // a box that turns all the time, to show that the app runs while audio is locked const material = new StandardMaterial(); material.diffuse = new Color(0.3, 0.75, 0.45); material.update(); const box = new Entity('box'); box.addComponent('render', { type: 'box', material }); app.root.addChild(box); // music that plays as soon as its component is enabled const music = new Entity('music'); music.addComponent('sound', { positional: false, volume: 0.5 }); const slot = music.sound.addSlot('music', { asset: asset.id, loop: true, autoPlay: true }); app.root.addChild(music); const context = app.systems.sound.context; // a start screen, shown while audio is locked. Its click unlocks audio, and as a button it works from the keyboard too const startScreen = document.createElement('button'); startScreen.style.cssText = 'position: absolute; left: 0; top: 0; width: 100%; height: 100%; border: 0; background: rgba(0, 0, 0, 0.65); color: #fff; font: 24px sans-serif; cursor: pointer;'; startScreen.textContent = 'Click to start'; startScreen.onclick = () => context.resume(); document.body.appendChild(startScreen); const showStartScreen = () => { startScreen.hidden = context.state === 'running'; }; context.addEventListener('statechange', showStartScreen); showStartScreen(); // suspend the audio context, to see the locked state again const lockButton = document.createElement('button'); lockButton.textContent = 'Lock audio'; lockButton.style.cssText = 'position: absolute; left: 12px; top: 12px;'; lockButton.onclick = () => context.suspend(); document.body.appendChild(lockButton); const status = document.createElement('div'); status.style.cssText = 'position: absolute; left: 12px; bottom: 10px; color: #ccc; font: 14px sans-serif;'; document.body.appendChild(status); app.on('update', (dt) => { box.rotate(10 * dt, 20 * dt, 0); const instance = slot.instances[0]; const position = instance ? instance.currentTime.toFixed(1) : '0.0'; status.textContent = `Audio context: ${context.state}. Slot playing: ${slot.isPlaying}. Music position: ${position}`; }); ``` Some things to try: - Click **Lock audio**. The start screen comes back, and the music's position stops, although the slot still reports that it is playing. - Reload the page and scroll here without clicking anything. The example starts locked, with the music held at 0. - Remove `autoPlay: true`, and start the music from the start screen's click instead, with `slot.play()`. ## See Also - [Getting Started](https://developer.playcanvas.com/user-manual/audio/getting-started.md#the-first-click) - The short version of this page - [Playing Sounds](https://developer.playcanvas.com/user-manual/audio/playing-sounds.md#auto-play) - Slots that play automatically - [Troubleshooting](https://developer.playcanvas.com/user-manual/audio/troubleshooting.md) - Other reasons for silence - [Autoplay guide for media and Web Audio APIs](https://developer.mozilla.org/en-US/docs/Web/Media/Guides/Autoplay) - MDN's account of the browser rules -------------------------------------------------------------------------------- ## Troubleshooting URL: https://developer.playcanvas.com/user-manual/audio/troubleshooting/ Markdown: https://developer.playcanvas.com/user-manual/audio/troubleshooting.md Each section below starts from what you hear, lists the usual causes, most likely first, and links to the page that explains each one. ## No Sound ### Nothing Plays at All - **Audio is locked.** Browsers keep audio off until the user clicks or taps the page. Sounds played before then start at the first click, and a key press does not count. See [Autoplay and User Gestures](https://developer.playcanvas.com/user-manual/audio/autoplay.md). - **The application has no sound system.** An Engine app built from `AppBase` needs a `SoundManager`, `SoundComponentSystem` and `AudioHandler`. Without the system, `addComponent('sound')` returns `null` and `entity.sound` is undefined. Without the handler, the asset fails with `No resource handler for asset type: 'audio'`. Without the sound manager, it fails with `Audio manager has no audio context`. See [Setting Up the Application](https://developer.playcanvas.com/user-manual/audio/getting-started.md#setting-up-the-application). - **The volume is 0.** Check the [master volume](https://developer.playcanvas.com/user-manual/audio/volume-and-mixing.md#master-volume), and the volume of the component and of the slot. A saved mute setting is easy to forget. - **The phone is set to silent.** On an iPhone, Web Audio is silent while the ring/silent switch is set to silent. See [Phones and Tablets](https://developer.playcanvas.com/user-manual/audio/autoplay.md#phones-and-tablets). ### One Sound Doesn't Play - **The slot name is wrong.** `play()` returns `null` for a name the component does not have. Names are case sensitive. - **The component or its entity is disabled.** `play()` does nothing and returns `null`. See [Enabling and Disabling](https://developer.playcanvas.com/user-manual/audio/playing-sounds.md#enabling-and-disabling). - **The slot has no asset**, or its asset failed to load. Listen for the asset's `error` event. A file that the browser cannot decode fails with `Unable to decode audio data`. - **The browser cannot decode the format.** A sound that plays in one browser and not in another is usually in a format that the second one does not support. See [Supported Formats](https://developer.playcanvas.com/user-manual/audio/audio-assets.md#supported-formats). - **The asset type was not recognized.** In Web Components, `` only recognizes `.mp3` files as audio by their extension. Give other formats `type="audio"`. - **It is too far away.** A positional sound beyond its `maxDistance` is silent with the linear distance model. See the next section. ## Positional Sounds ### A Sound Is Silent or Too Quiet - **The sound is positional, and should not be.** Sound components are positional by default. Music or an interface sound on a positional component fades as the camera moves away from its entity. Turn **Positional** off. See [Positional and Non-Positional Sounds](https://developer.playcanvas.com/user-manual/audio/positional-audio.md#positional-and-non-positional-sounds). - **The listener is not where you think.** With no audio listener, sounds are heard from the world origin, not from the camera. With several, only the one enabled most recently is used. A disabled listener goes on being heard from where it last was. See [The Audio Listener](https://developer.playcanvas.com/user-manual/audio/positional-audio.md#the-audio-listener). - **The source is beyond `maxDistance`.** With the linear model, a sound is silent from `maxDistance` outwards. ### A Sound Doesn't Fade with Distance The default `maxDistance` is 10,000, which fades a sound so gradually that it seems not to fade at all. Set `maxDistance` to the distance at which the sound should be silent, or use the inverse distance model. See [Distance](https://developer.playcanvas.com/user-manual/audio/positional-audio.md#distance). ### A Sound Doesn't Move Between the Speakers - **The component is not positional.** Only positional sounds are panned. - **The listener is on the sound's own entity**, or on one that moves with it. A sound at the listener's position is always in the middle. - **The sound is in front or behind.** Sounds are panned left and right only, so a sound that crosses from front to back does not change. See [Panning](https://developer.playcanvas.com/user-manual/audio/positional-audio.md#panning). ## Playback ### Sounds Cut Each Other Off A slot plays one sound at a time, so playing it again restarts it. Turn **Overlap** on for sounds that should pile up, such as gunshots and footsteps. See [Overlapping Sounds](https://developer.playcanvas.com/user-manual/audio/playing-sounds.md#overlapping-sounds). ### A Sound Goes On After Its Entity Is Destroyed Sounds on an overlapping slot play to their end, even when the entity is destroyed or disabled. Stop the slot before you destroy the entity, or turn **Overlap** off. ### Changing Volume or Pitch Does Nothing On an overlapping slot, changes to `volume`, `pitch`, `startTime` and `duration` apply to the next play, not to sounds that are already playing. The same is true of the `volume` and `pitch` of the sound component. To change a sound that is playing, set the property on its [sound instance](https://developer.playcanvas.com/user-manual/audio/controlling-playback.md#volume-and-pitch). ### A Burst of Sound at the First Click One-shot sounds that were played while audio was locked all start together when it unlocks. Skip them while the audio context is not running. See [Sounds Played While Locked](https://developer.playcanvas.com/user-manual/audio/autoplay.md#sounds-played-while-locked). ### A Sound Is Late the First Time The asset had not loaded. A slot that is played before its asset is ready plays once the file has downloaded and decoded. Preload the asset, or load it before it is needed. See [When Audio Loads](https://developer.playcanvas.com/user-manual/audio/audio-assets.md#when-audio-loads). ### A Loop Has a Gap or a Click The engine loops without a gap, so the gap is in the file: silence at its ends, or a loop that is not cut on a musical boundary. See [Seamless Loops](https://developer.playcanvas.com/user-manual/audio/audio-assets.md#seamless-loops). ### The `end` Event Never Fires - **The sound loops.** A looping sound never reaches its end. - **The sound was stopped.** A sound that is stopped fires `stop`, not `end`. Listen for `stop` to act either way. - **You listened on an old instance.** Each play creates a new [sound instance](https://developer.playcanvas.com/user-manual/audio/controlling-playback.md#sound-instances). Listen on the slot or the component instead, which fire for every play. ## Effects ### An Error When Clearing Effects `clearExternalNodes()` throws an `InvalidAccessError` when the slot shares its nodes with a slot that has already been cleared. Do not clear slots that share nodes. See [Sharing Effects](https://developer.playcanvas.com/user-manual/audio/effects.md#sharing-effects). ### An Effect Does Nothing - **The nodes are not connected to each other.** With two nodes passed to `setExternalNodes()`, the engine connects the sound to the first and the last to the speakers. The connections between them are yours to make. - **The nodes came from another audio context.** Create them from `app.systems.sound.context`. - **The slot overlaps.** Nodes set on an overlapping slot apply to the next play. ## Memory ### Audio Uses a Lot of Memory Every loaded sound is held in memory decoded, at about 11 MB for each minute of mono audio, however small its file is. Use mono for sound effects, loop short sections of music rather than loading long tracks, and unload assets you have finished with. See [Memory](https://developer.playcanvas.com/user-manual/audio/audio-assets.md#memory). ## See Also - [Autoplay and User Gestures](https://developer.playcanvas.com/user-manual/audio/autoplay.md) - Why audio waits for a click - [Audio Assets](https://developer.playcanvas.com/user-manual/audio/audio-assets.md) - Formats, loading and memory - [Positional Audio](https://developer.playcanvas.com/user-manual/audio/positional-audio.md) - The listener and distance models -------------------------------------------------------------------------------- ## 2D URL: https://developer.playcanvas.com/user-manual/2D/ Markdown: https://developer.playcanvas.com/user-manual/2D.md The PlayCanvas Engine is designed to make creating 3D games and applications fast and simple. However, we also support a number of great features for creating 2D games. With PlayCanvas' 2D features you get all the benefits of a powerful 3D engine but for 2D games. ## Basic Features ### Sprites [Image: Sprite] 2D graphics are often known as **Sprites**. In PlayCanvas you can create [Sprite Assets](https://developer.playcanvas.com/user-manual/editor/assets/inspectors/sprite.md) and [Sprite Components](https://developer.playcanvas.com/user-manual/editor/scenes/components/sprite.md). The Sprite Component is attached to Entities in order to display 2D graphics in your scene. Sprite Assets in PlayCanvas store multiple image frames from a Texture Atlas in sequence. So you can use a Sprite Asset to create flip-book style animated graphics in your games. ### Texture Atlases [Image: Texture Atlas] A [Texture Atlas](https://developer.playcanvas.com/user-manual/editor/assets/inspectors/texture-atlas.md) is an enhanced version of the standard [Texture](https://developer.playcanvas.com/user-manual/editor/assets/inspectors/texture.md) asset. In addition to the regular texture features, a Texture Atlas includes the definitions of a set of "Frames". Each frame is a region of the texture which can be referenced in a Sprite Asset. ### Sprite Editor [Image: Sprite Editor] The [Sprite Editor](https://developer.playcanvas.com/user-manual/2D/sprite-editor.md) is the tool used to generate Texture Atlas frames and Sprite Assets. You can open the Sprite Editor by double-clicking on any Texture Atlas or Sprite Asset. [Read More](https://developer.playcanvas.com/user-manual/2D/sprite-editor.md). *Artwork created by [PixelBoy](https://twitter.com/2pblog1)* ## Skeletal Animation ### Spine [Image: Spine] [Spine](https://esotericsoftware.com/) is an editor for 2D skeletal animation. The [playcanvas-spine](https://github.com/playcanvas/playcanvas-spine) plugin plays animations exported from Spine, in Editor and engine-only projects. [Read More](https://developer.playcanvas.com/user-manual/engine/libraries/spine.md). -------------------------------------------------------------------------------- ## Sprite Editor URL: https://developer.playcanvas.com/user-manual/2D/sprite-editor/ Markdown: https://developer.playcanvas.com/user-manual/2D/sprite-editor.md The Sprite Editor is used to edit both Texture Atlas assets and Sprite assets. It is also used to create Sprite Assets. To open the Sprite Editor, double-click on any Texture Atlas or Sprite asset in the Editor asset panel. [Image: Sprite Editor] ## Viewport [Image: Viewport] The viewport in the Sprite Editor shows the currently selected Texture Atlas. Frames are shown as grey boxes on the texture atlas. The currently selected asset is shown with two sets of handles. green and blue. Green handles modify the frame's width and height, blue handles modify the frame's border property. ### Editing Texture Atlases Within the viewport use the mouse to drag the outline of a Frame, then use the green and blue handles to modify the frames extents and borders. #### Frames Frames are a defined region on a Texture Atlas. A frame has a name, a position and size and a border. The border is used to define the edges of the 9-slicing region. See the [9-slicing documentation](https://developer.playcanvas.com/user-manual/2D/slicing.md) for more information. ## Inspector The inspector panel shows the properties of the currently selected item. The inspector changes depending on whether the selected item is a Texture Atlas, Frame or Sprite Asset. ### Texture Atlas Inspector [Image: Texture Atlas Inspector] The Texture Atlas Inspector allows you to automatically slice a texture atlas into a fixed grid. First choose what to do with existing frames. You can choose to *Delete Existing* frames or do not delete and *Only Append* frames. Then select the method of specifying the grid cells - Grid By Frame Count - Specify the number of grid cells horizontally and vertically to divide the texture into - Grid By Frame Size - Specify the size in pixels that each grid cell should be Then set the values for Offset and Spacing. Offset is the number of pixels to move in from the top left of the texture before starting the grid. Spacing is the number of pixels between each grid cell. Finally set the pivot for all newly generated frames, the pivot determines the position and rotation point of the sprite. It is specified as a proportion of the width and height. Once all your settings are chosen, click the **Generate Frames** button to create your frames. ### Frame Inspector [Image: Frame Inspector] The Frame Inspector lets you set the properties for an individual frame or group of frames. It is visible when you select one or more Frames. The Frame Inspector is also where you create a new Sprite from. The Inspector lets you modify the Position, Size and Border properties of the frame. #### Frame Inspector Actions - **New Sprite From Selection** - Create a new Sprite Asset and assign the frames that you have selected to the Sprite, in the order that they were selected. - **New Sliced Sprite From Selection** - Create a new Sprite Asset and set its type to *Sliced*. Assign the frames that you have selected to the Sprite, in the order that they were selected. - **Focus on Selection** - Focus the viewport on the selected Frames. [Keyboard Shortcut: F] - **Trim Selected Frames** - Reduce the size of the selected frames to remove any excess empty space around an image. [Keyboard Shortcut: T] - **Delete Selected Frames** - Delete the selected Frames [Keyboard Shortcut: Delete] ### Sprite Inspector [Image: Sprite Inspector] The Sprite Inspector is visible when a Sprite Asset is selected. This inspector is used to edit the properties of one or more Sprites. See the [Sprite Asset](https://developer.playcanvas.com/user-manual/editor/assets/inspectors/sprite.md) for more details on the properties. Click the **Add Frames to Sprite Asset** button to enter the Sprite Edit Mode. In this mode, you can select multiple frames from the Frame Panel or Viewport and add them to the Sprite. Click the **Add Selected Frames** to add the frames to your Sprite. Using the Sprite Inspector you can also re-order the Frames in your Sprite, or delete individual Frames. ## Frames Panel The Frames Panel lets you select and delete Frames from the Texture Atlas ## Asset Panel The Asset Panel shows you all the Sprite Assets that have been created from the current Texture Atlas. You can select Sprite Assets from this panel. *Artwork created by [PixelBoy](https://twitter.com/2pblog1)* -------------------------------------------------------------------------------- ## 9-slicing URL: https://developer.playcanvas.com/user-manual/2D/slicing/ Markdown: https://developer.playcanvas.com/user-manual/2D/slicing.md 9-slicing (sometimes called 9-patch) is a technique for 2D graphics that splits a single image into 9 areas which are scaled individually in order to prevent stretching when the image is displayed at different sizes and with different aspect ratios. [Image: 9 Sliced Button] In the image above you can see the 9 areas that a defined using the Texture Atlas editing features of the [Sprite Editor](https://developer.playcanvas.com/user-manual/2D/sprite-editor.md). When added to a scene using either a [Sprite Component](https://developer.playcanvas.com/user-manual/editor/scenes/components/sprite.md) or an [Image Element Component](https://developer.playcanvas.com/user-manual/editor/scenes/components/element.md), the image can be resized using the width and height properties of the component. Each area is scaled using the following rules: * **Center** - stretch or tile both horizontally and vertically * **Top, Bottom** - stretch or tile horizontally only * **Left, Right** - stretch or tile vertically only * **TopLeft, TopRight, BottomLeft, BottomRight** - Do not stretch or tile [Image: Button Resize Animation] ## Setting up 9-slicing [Image: Setup 9-slicing] To setup a 9-sliced sprite. Create a frame around the area that you wish to use 9-slicing on in the Sprite Editor. Then use the blue handles or the Border property in the Frame Inspector to set the borders to outline the center portion of the image that you wish to be the stretch part of your sprite. Finally click the **New Sliced Sprite From Selection** to create a new Sprite with the render mode set to *Sliced*. ## Render Modes Sprite Assets can have one of three Render Modes. ### Simple Sprites [Image: Simple Render Mode] *Simple* Render Mode has no 9-slicing. Use this mode for regular sprites. ### Sliced Sprites [Image: Sliced Render Mode] *Sliced* Render Mode stretches portions of the image. The center stretches horizontally and vertically; the left and right sections stretch vertically; the top and bottom sections stretch horizontally and the corners do not stretch at all. ### Tiled Sprites [Image: Tiled Render Mode] *Tiled* Render Mode is similar to *Sliced* mode except instead of stretching the sections repeat in a tiled manner. The center tiles horizontally and vertically; the left and right tile vertically; the top and bottom tile horizontally and the corners do not tile at all. -------------------------------------------------------------------------------- ## Using Texture Packers URL: https://developer.playcanvas.com/user-manual/2D/texture-packing/ Markdown: https://developer.playcanvas.com/user-manual/2D/texture-packing.md ## What is texture packing? It's common to find sprites or UI images bundled as separate images. Texture packing is combining those separate images into a single [texture atlas](https://developer.playcanvas.com/user-manual/editor/assets/inspectors/texture-atlas.md). This has several advantages including: - Faster loading times as it's a single network request instead of many. - As it's a single texture, the sprites can be batched into a single draw call. ## Tools Here are some texture packing tools that are compatible with PlayCanvas. ### TexturePacker Online (free) ([Website](https://www.codeandweb.com/tp-online)) A free browser tool that is able to do the basics of texture packing. 1. Clear the texture atlas. 2. Add your sprites/UI images. 3. Data format should be kept as JSON hash. 4. Download .png for the texture atlas. 5. Download .json for the frame data. ### Texture Packer tool ([Website](https://www.codeandweb.com/texturepacker)) TexturePacker is a paid tool for download that has many more features and options for creating texture atlases. These include more control over the layout of the sprites/UI images and being able to set up [9 slicing](https://developer.playcanvas.com/user-manual/2D/slicing.md). Basic steps: 1. Add your sprites/UI images. 2. Set Output files -> Framework as PlayCanvas. 3. Click on Publish sprite sheet to create the texture atlas and JSON frame data. ## Creating frames in Sprite Editor Once you have uploaded the texture atlas file into the Editor and created a [texture atlas asset](https://developer.playcanvas.com/user-manual/editor/assets/inspectors/texture-atlas.md), open the Sprite Editor. Click on 'Upload Texture Packer JSON' and select the JSON frame data file to upload. This will create frames in the texture atlas that you can create sprite assets from. When updating the texture atlas later in development, as long as the sprite filenames and frame names remain the same, the following will happen when uploading the new frame data: - Sprites that have been removed on the atlas will have their frames removed. - Sprites that have been added on the atlas will have new frames added to the end of the list. - Existing sprites will have their frames updated. -------------------------------------------------------------------------------- ## User Interface URL: https://developer.playcanvas.com/user-manual/user-interface/ Markdown: https://developer.playcanvas.com/user-manual/user-interface.md Almost every application needs an interface: a HUD, menus, buttons, dialogs, labels in the scene, or a panel in XR. PlayCanvas lets you build them inside the canvas, from entities, as part of the scene, or outside it with HTML and CSS, and many applications combine the two. [Image: A game interface over a 3D scene: a list in a scrolling panel, a round portrait, health and energy bars, a row of buttons and a toolbar] In-canvas UI is built from components. A [screen](https://developer.playcanvas.com/user-manual/user-interface/screens.md) is the root of an interface, and [elements](https://developer.playcanvas.com/user-manual/user-interface/elements.md) below it are its images, text and groups. Components such as buttons, layout groups and scroll views add behavior on top. They are available whichever way you build: in the Editor, directly against the engine, in [PlayCanvas React](https://developer.playcanvas.com/user-manual/react.md) and in [Web Components](https://developer.playcanvas.com/user-manual/web-components.md). Each page in this section explains a concept once and then shows how to apply it on each of those surfaces. ## Two Ways to Build UI | | In-canvas UI | HTML and CSS | | --- | --- | --- | | **World space and XR** | Screens can be placed in the scene, and work in XR | Only over the canvas | | **Text input** | None built in | Text fields, autocomplete, the on-screen keyboard | | **Accessibility** | Not visible to screen readers or keyboard navigation | Accessible with the right elements | | **Styling and layout** | Anchors, layout groups, 9-sliced sprites | CSS, with the browser's layout and animation | | **Fonts and emoji** | MSDF fonts made from your font files, emoji through a canvas font | Every web font and emoji | | **Editor** | Built and previewed in the Editor | Written as HTML and CSS assets or files | | **Canvas capture** | Part of screenshots and video captures of the canvas | Not in captures of the canvas | | **Performance** | Drawn with the scene, and batched | Laid out and painted by the browser beside the canvas | In-canvas UI suits HUDs, interfaces in the scene or in XR, and anything that must be part of what the canvas shows. HTML suits menus, settings, forms and long text. They mix well: an HTML settings screen can pause an application whose HUD is in the canvas. See [HTML and CSS](https://developer.playcanvas.com/user-manual/user-interface/html-and-css.md). ## Building Blocks | Component | Role | Editor | React | Web Components | API | | --- | --- | --- | --- | --- | --- | | Screen | The root of an interface, over the view or in the scene | [Screen](https://developer.playcanvas.com/user-manual/editor/scenes/components/screen.md) | [``](https://developer.playcanvas.com/user-manual/react/api/screen.md) | [``](https://developer.playcanvas.com/user-manual/web-components/tags/pc-screen.md) | [ScreenComponent](https://api.playcanvas.com/engine/classes/ScreenComponent.html) | | Element | An image, a text or a group | [Element](https://developer.playcanvas.com/user-manual/editor/scenes/components/element.md) | [``](https://developer.playcanvas.com/user-manual/react/api/element.md) | [``](https://developer.playcanvas.com/user-manual/web-components/tags/pc-element.md) | [ElementComponent](https://api.playcanvas.com/engine/classes/ElementComponent.html) | | Button | Hover and press states, and click events | [Button](https://developer.playcanvas.com/user-manual/editor/scenes/components/button.md) | [Engine component](https://developer.playcanvas.com/user-manual/user-interface/buttons.md#creating-a-button) | [``](https://developer.playcanvas.com/user-manual/web-components/tags/pc-button.md) | [ButtonComponent](https://api.playcanvas.com/engine/classes/ButtonComponent.html) | | Layout Group | Arranges children in rows, columns and grids | [Layout Group](https://developer.playcanvas.com/user-manual/editor/scenes/components/layoutgroup.md) | [Engine component](https://developer.playcanvas.com/user-manual/user-interface/layout-groups.md#creating-a-layout-group) | [``](https://developer.playcanvas.com/user-manual/web-components/tags/pc-layout-group.md) | [LayoutGroupComponent](https://api.playcanvas.com/engine/classes/LayoutGroupComponent.html) | | Layout Child | Overrides how a layout group sizes a child | [Layout Child](https://developer.playcanvas.com/user-manual/editor/scenes/components/layoutchild.md) | [Engine component](https://developer.playcanvas.com/user-manual/user-interface/layout-groups.md#layout-children) | [``](https://developer.playcanvas.com/user-manual/web-components/tags/pc-layout-child.md) | [LayoutChildComponent](https://api.playcanvas.com/engine/classes/LayoutChildComponent.html) | | Scroll View | Scrolls content inside a masked viewport | [Scroll View](https://developer.playcanvas.com/user-manual/editor/scenes/components/scrollview.md) | [Engine component](https://developer.playcanvas.com/user-manual/user-interface/scroll-views.md#creating-a-scroll-view) | [``](https://developer.playcanvas.com/user-manual/web-components/tags/pc-scroll-view.md) | [ScrollViewComponent](https://api.playcanvas.com/engine/classes/ScrollViewComponent.html) | | Scrollbar | A draggable handle on a track, for scroll views and sliders | [Scrollbar](https://developer.playcanvas.com/user-manual/editor/scenes/components/scrollbar.md) | [Engine component](https://developer.playcanvas.com/user-manual/user-interface/scroll-views.md#creating-a-scroll-view) | [``](https://developer.playcanvas.com/user-manual/web-components/tags/pc-scrollbar.md) | [ScrollbarComponent](https://api.playcanvas.com/engine/classes/ScrollbarComponent.html) | PlayCanvas React has components for screens and elements. The others are added as engine components, with a small helper that each page shows. ## In This Section - [Getting Started](https://developer.playcanvas.com/user-manual/user-interface/user-interface-basics.md) - Setting up UI on each surface, and a first interface. - **Layout** - [Screens](https://developer.playcanvas.com/user-manual/user-interface/screens.md) - Screen space and world space, scaling to any canvas, pixel ratio and priority. - [Elements](https://developer.playcanvas.com/user-manual/user-interface/elements.md) - Anchors, pivots, margins, sizes and group elements. - [Layout Groups](https://developer.playcanvas.com/user-manual/user-interface/layout-groups.md) - Rows, columns and grids that arrange their children. - [Safe Areas](https://developer.playcanvas.com/user-manual/user-interface/safe-area.md) - Keeping an interface clear of notches and rounded corners. - **Images** - [Image Elements](https://developer.playcanvas.com/user-manual/user-interface/image-elements.md) - Colors, textures, sprites, 9-slicing, 3D in an image and custom materials. - [Masks](https://developer.playcanvas.com/user-manual/user-interface/masks.md) - Clipping children to a rectangle or a shape. - **Text** - [Text Elements](https://developer.playcanvas.com/user-manual/user-interface/text-elements.md) - Size, wrapping, fitting, justification, markup, outlines and shadows. - [Fonts](https://developer.playcanvas.com/user-manual/user-interface/fonts.md) - Creating and loading font assets, and choosing their characters. - [Localization](https://developer.playcanvas.com/user-manual/user-interface/localization.md) - Translations, plurals, locales and fonts for each language. - **Interaction** - [Input](https://developer.playcanvas.com/user-manual/user-interface/input.md) - Mouse, touch and XR events, bubbling, and keeping UI input from the game. - [Buttons](https://developer.playcanvas.com/user-manual/user-interface/buttons.md) - Hover and press states, tints, sprites and events. - [Scroll Views](https://developer.playcanvas.com/user-manual/user-interface/scroll-views.md) - Scrolling content by dragging, the wheel and scrollbars. - [Common Widgets](https://developer.playcanvas.com/user-manual/user-interface/common-widgets.md) - Progress bars, sliders, toggles, dialogs, lists, drag and drop and more. - **World Space and XR** - [World-Space UI](https://developer.playcanvas.com/user-manual/user-interface/world-space-ui.md) - Interfaces in the scene, and labels over characters. - [UI in XR](https://developer.playcanvas.com/user-manual/user-interface/xr.md) - Panels, pointing, hands and menus in immersive sessions. - [HTML and CSS](https://developer.playcanvas.com/user-manual/user-interface/html-and-css.md) - Interfaces built with the DOM over the canvas. - [Draw Order and Performance](https://developer.playcanvas.com/user-manual/user-interface/draw-order-and-performance.md) - How UI is drawn, and keeping it fast. - [Troubleshooting](https://developer.playcanvas.com/user-manual/user-interface/troubleshooting.md) - Common problems and their causes. ## See Also - [User Interface - Buttons](https://developer.playcanvas.com/tutorials/ui-elements-buttons/), [Leaderboard](https://developer.playcanvas.com/tutorials/ui-elements-leaderboard/) and [Progress Bar](https://developer.playcanvas.com/tutorials/ui-elements-progress/) - Tutorials that build interfaces in the Editor - [User Interface - Text Input](https://developer.playcanvas.com/tutorials/ui-text-input/) - Tutorial that builds a text field - [Touchscreen Joypad Controls](https://developer.playcanvas.com/tutorials/touch-joypad/) - Tutorial that builds on-screen joysticks - [2D](https://developer.playcanvas.com/user-manual/2D.md) - Sprites, texture atlases and 9-slicing - [PCUI](https://playcanvas.github.io/pcui/) - The HTML component library for building tools and editors -------------------------------------------------------------------------------- ## Getting Started URL: https://developer.playcanvas.com/user-manual/user-interface/user-interface-basics/ Markdown: https://developer.playcanvas.com/user-manual/user-interface/user-interface-basics.md An in-canvas user interface is a tree of entities. At its root is an entity with a [screen](https://developer.playcanvas.com/user-manual/user-interface/screens.md) component, which defines the space the interface lives in. Below it, entities with [element](https://developer.playcanvas.com/user-manual/user-interface/elements.md) components are the rectangles you see: images, text and invisible groups that hold other elements. Components such as [buttons](https://developer.playcanvas.com/user-manual/user-interface/buttons.md) and [scroll views](https://developer.playcanvas.com/user-manual/user-interface/scroll-views.md) add behavior on top. This page sets up UI on each surface and builds a small interface: a panel with a label and a button that counts its clicks. [Image: A dark panel in the middle of the screen with the text "Hello, PlayCanvas!" above an orange "Click me" button] ## Setting Up Screens and elements are drawn by any application that includes their component systems. To respond to input, an application also needs an [`ElementInput`](https://api.playcanvas.com/engine/classes/ElementInput.html), the object that turns mouse, touch and XR events into events on elements. **Engine** Register the UI component systems, the font and texture handlers, and an `ElementInput` when you create the application: ```javascript const canvas = document.getElementById('application'); const device = await createGraphicsDevice(canvas, { deviceTypes: [DEVICETYPE_WEBGPU] }); const options = new AppOptions(); options.graphicsDevice = device; // Create the ElementInput before the mouse and touch devices, so that calling // stopPropagation() in a UI event handler also hides the event from them options.elementInput = new ElementInput(canvas); options.mouse = new Mouse(canvas); options.touch = new TouchDevice(canvas); options.componentSystems = [ CameraComponentSystem, ScreenComponentSystem, ElementComponentSystem, ButtonComponentSystem ]; options.resourceHandlers = [ FontHandler, TextureHandler ]; const app = new AppBase(canvas); app.init(options); app.setCanvasFillMode(FILLMODE_FILL_WINDOW); app.setCanvasResolution(RESOLUTION_AUTO); app.start(); window.addEventListener('resize', () => app.resizeCanvas()); ``` Add the systems of the other UI components as you use them: `ScrollViewComponentSystem`, `ScrollbarComponentSystem`, `LayoutGroupComponentSystem` and `LayoutChildComponentSystem`, plus `SpriteHandler` and `TextureAtlasHandler` for sprites. [`Application`](https://api.playcanvas.com/engine/classes/Application.html) registers every system and handler for you, but it does not create an `ElementInput` either, so pass one in its options. See [Using the Engine Standalone](https://developer.playcanvas.com/user-manual/engine/standalone.md#configuring-the-application) for the rest of the setup. **Editor** There is nothing to set up. Launched and published applications create the `ElementInput` for you, using the mouse and touch settings in the [INPUT](https://developer.playcanvas.com/user-manual/editor/interface/settings/input.md) section of the Settings panel. UI does not respond to input in the Editor viewport. Launch the scene to try your buttons and scroll views. **React** There is nothing to set up. `` creates the `ElementInput`, together with the mouse and touch devices. **Web Components** There is nothing to set up. `` creates the `ElementInput`, together with the mouse and keyboard devices. ## Your First Interface The interface in the image above is a screen with a panel on it. The panel holds a label and a button, and the button holds its own text. Text needs a [font asset](https://developer.playcanvas.com/user-manual/user-interface/fonts.md); the code on this page loads one called `arial.json`, which you can generate from any font file. **Engine** With the application set up as above: ```javascript // Load a font for the text const font = new Asset('arial', 'font', { url: 'fonts/arial.json' }); app.assets.add(font); await new Promise((resolve) => { font.ready(resolve); app.assets.load(font); }); const camera = new Entity('camera'); camera.addComponent('camera', { clearColor: new Color(0.1, 0.11, 0.13) }); app.root.addChild(camera); // A screen-space screen that scales with the canvas const screen = new Entity('screen'); screen.addComponent('screen', { screenSpace: true, referenceResolution: [1280, 720], scaleMode: SCALEMODE_BLEND, scaleBlend: 0.5 }); app.root.addChild(screen); // A panel in the middle of the screen const panel = new Entity('panel'); panel.addComponent('element', { type: ELEMENTTYPE_IMAGE, anchor: [0.5, 0.5, 0.5, 0.5], pivot: [0.5, 0.5], width: 420, height: 240, color: new Color(0.16, 0.18, 0.23), opacity: 0.9 }); screen.addChild(panel); // A label near the top of the panel const label = new Entity('label'); label.addComponent('element', { type: ELEMENTTYPE_TEXT, fontAsset: font.id, text: 'Hello, PlayCanvas!', fontSize: 36, anchor: [0.5, 1, 0.5, 1], pivot: [0.5, 1] }); label.setLocalPosition(0, -40, 0); panel.addChild(label); // A button near the bottom: an image element that receives input, and a // button component that tints the image when it is hovered and pressed const button = new Entity('button'); button.addComponent('element', { type: ELEMENTTYPE_IMAGE, anchor: [0.5, 0, 0.5, 0], pivot: [0.5, 0], width: 200, height: 60, color: new Color(1, 0.55, 0.2), useInput: true }); button.addComponent('button', { imageEntity: button, hoverTint: new Color(1, 0.7, 0.45), pressedTint: new Color(0.8, 0.4, 0.1) }); button.setLocalPosition(0, 40, 0); panel.addChild(button); const buttonText = new Entity('text'); buttonText.addComponent('element', { type: ELEMENTTYPE_TEXT, fontAsset: font.id, text: 'Click me', fontSize: 28, color: new Color(0.1, 0.1, 0.1), anchor: [0.5, 0.5, 0.5, 0.5], pivot: [0.5, 0.5] }); button.addChild(buttonText); // Count the clicks let clicks = 0; button.button.on('click', () => { clicks++; label.element.text = `Clicked ${clicks} times`; }); ``` **Editor** 1. Upload a `.ttf` or `.otf` file to create a [font asset](https://developer.playcanvas.com/user-manual/user-interface/fonts.md#in-the-editor). 2. In the Hierarchy, click **+** and choose **User Interface โ€บ 2D Screen**. New entities are added below the selected entity, so keep the screen selected for the next step. 3. Add a **User Interface โ€บ Image Element** and rename it `Panel`. In its Element component, set **Preset** to **Center Anchor & Pivot**, **Width** to 420, **Height** to 240, and pick a dark **Color** with an **Opacity** of 0.9. 4. With the panel selected, add a **User Interface โ€บ Text Element** and rename it `Label`. Set **Preset** to **Top Anchor & Pivot**, the entity's position to (0, -40, 0), **Font** to your font asset, **Text** to `Hello, PlayCanvas!` and **Font Size** to 36. 5. With the panel selected again, add a **User Interface โ€บ Button**. This creates a `Button` entity, whose image element has **Use Input** enabled and whose button component already uses it as its **Image**, with a `Text` child. Set the button's **Preset** to **Bottom Anchor & Pivot**, its position to (0, 40, 0), its size to 200 ร— 60 and its **Color** to orange, set **Hover Tint** and **Pressed Tint** to lighter and darker oranges, and set the child's **Text** to `Click me`. 6. Add a **Script** component to the `Button`, attach this script and drag the `Label` entity onto its **Label** attribute: ```javascript import { Entity, Script } from 'playcanvas'; export class ClickCounter extends Script { static scriptName = 'clickCounter'; /** * The text element that shows the count. * * @attribute * @type {Entity} */ label; clicks = 0; initialize() { this.entity.button.on('click', () => { this.clicks++; this.label.element.text = `Clicked ${this.clicks} times`; }); } } ``` 7. Launch the scene and click the button. **React** Render `FirstInterface` inside an ``. There is no `