### Dynamically Install Scene Plugin in init() Source: https://docs.phaser.io/phaser/concepts/scenes This example illustrates how to dynamically install a default plugin (TweenManager) into a Phaser Scene after it has been created, using the `init` method. This approach is beneficial when the need for a plugin is determined during the scene's initialization phase. ```javascript class BootScene extends Phaser.Scene { constructor() { super({ key: 'boot', plugins: [] }); } init() { this.sys.install('TweenManager'); } } ``` -------------------------------- ### Two-Scene Game Structure (Boot and Play) Source: https://docs.phaser.io/phaser/concepts/scenes Provides a concrete example of a two-scene game structure, with a 'Boot' scene for loading assets and a 'Play' scene for game logic. The 'Boot' scene is configured to start automatically. ```javascript class Boot extends Phaser.Scene { // Load assets preload() {} // Start Play scene create() {} } class Play extends Phaser.Scene { // Create game objects with loaded assets create() {} // Update the scene update() {} } new Phaser.Game({ scene: [ // Only 'boot' will start. new Boot("boot"), new Play("play"), ], }); ``` -------------------------------- ### Transitioning between scenes using start() Source: https://docs.phaser.io/phaser/concepts/scenes Demonstrates how to transition from one scene to another using the start() method. This method stops the calling scene and starts the target scene. ```javascript // In scene A: stop A, start B this.scene.start("B"); // In scene B: stop B, start C this.scene.start("C"); // In scene C: stop C, start A again this.scene.start("A"); ``` -------------------------------- ### macOS Custom Browser Path Example Source: https://docs.phaser.io/phaser-editor/workbench/settings Example of a macOS path for a custom browser executable. Paths containing spaces should be enclosed in quotes. ```text "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" ``` -------------------------------- ### Animation Creation Examples Source: https://docs.phaser.io/phaser/concepts/animations Provides practical examples of creating animations using different methods, including using all frames from a texture, selecting specific frames, and generating animations from multiple textures. ```APIDOC ## POST /anims/create Examples ### Description Illustrates various ways to define animations using `this.anims.create()`. ### Method POST ### Endpoint /anims/create ### Examples #### 1. Use every frame in a texture Creates an animation named 'mummyWalk' using all frames from the 'mummy' texture. ```javascript this.anims.create({ key: "mummyWalk", frames: "mummy" }); ``` #### 2. Choosing specific texture frames by index Creates an animation named 'mummyWalk' using frames 0, 1, and 2 from the 'mummy' texture. ```javascript this.anims.create({ key: "mummyWalk", frames: [ { key: "mummy", frame: 0 }, { key: "mummy", frame: 1 }, { key: "mummy", frame: 2 } ] }); ``` #### 3. Creating animations from multiple textures with shared frame patterns Generates animations like 'giant:idle', 'elf:walk', etc., by iterating through texture keys and predefined animation sequences. ```javascript const textureKeys = ["giant", "elf", "goblin"]; const anims = { idle: [0], walk: [1, 2], attack: [3, 4] }; for (const textureKey of textureKeys) { for (const animName in anims) { this.anims.create({ key: `${textureKey}:${animName}`, frames: anims[animName].map(frameIndex => ({ key: textureKey, frame: frameIndex })) }); } } ``` ### Response (See general response for `POST /anims/create`) ``` -------------------------------- ### Starting the Dev Server Automatically Source: https://docs.phaser.io/phaser-editor/v4/workbench/playing-project To have Phaser Editor run the web server for you, click the 'Start Dev Server' button. This is the recommended approach if you want the editor to manage the server process. ```text Start Dev Server button ``` -------------------------------- ### Install a Script Library Source: https://docs.phaser.io/phaser-editor/scene-editor/script-node/script-node-libraries Use npm to install a script library into your project. This command adds the specified library to your project's dependencies. ```bash npm install @phaserjs/editor-scripts-quick ``` -------------------------------- ### Texture Config Property Example (Image) Source: https://docs.phaser.io/phaser-editor/scene-editor/prefabs/prefab-user-properties Represents a texture selected from an Asset Pack. This example shows the configuration for a simple image texture. ```json { "key": "background" } ``` -------------------------------- ### Read 'start' URL parameter to preview scene Source: https://docs.phaser.io/phaser-editor/v4/scene-editor/misc This code snippet reads the 'start' URL parameter to dynamically load a specific scene when previewing the game in development. It should be placed in a scene that runs early in the game's lifecycle, like the Preloader. ```javascript if (process.env.NODE_ENV === "development") { const start = new URLSearchParams(location.search).get("start"); if (start) { console.log(`Development: jump to ${start}`); this.scene.start(start); return; } } ``` -------------------------------- ### Get Start and End Points of Path or Curve Source: https://docs.phaser.io/phaser/concepts/math Retrieves the starting and ending coordinates of a path or curve. The 'out' parameter can be used to modify an existing point object. ```javascript var out = path.getStartPoint(); // var out = path.getStartPoint(out); ``` ```javascript var out = curve.getStartPoint(); // var out = curve.getStartPoint(out); ``` ```javascript var out = path.getEndPoint(); // var out = path.getEndPoint(out); ``` ```javascript var out = curve.getEndPoint(); // var out = curve.getEndPoint(out); ``` -------------------------------- ### Display Server Help Source: https://docs.phaser.io/phaser-editor/misc/server-options Use the `--help` option to view all available server configuration commands. ```bash $ PhaserEditor --help ``` -------------------------------- ### Display Server Help Source: https://docs.phaser.io/phaser-editor/v4/misc/server-options Use the `--help` option to view all available server commands and their descriptions. ```bash PhaserEditor --help ``` -------------------------------- ### Phaser Arc Properties: Get and Set Angle Source: https://docs.phaser.io/phaser/concepts/gameobjects/graphics Demonstrates how to get and set the start and end angles, as well as the anticlockwise property of a Phaser Arc object. These properties control the arc's orientation and direction. ```javascript var startAngle = arc.startAngle; arc.setStartAngle(startAngle); // arc.setStartAngle(startAngle, anticlockwise); arc.startAngle = startAngle; var endAngle = arc.endAngle; arc.seEndAngle(endAngle); arc.endAngle = endAngle; var anticlockwise = arc.anticlockwise; arc.anticlockwise = anticlockwise; ``` -------------------------------- ### Phaser Circle Properties: Get and Set Radius and Iterations Source: https://docs.phaser.io/phaser/concepts/gameobjects/graphics Provides code examples for getting and setting the radius and iterations (for smoother arcs) of a Phaser Circle object. The radius determines the circle's size, and iterations affect its smoothness. ```javascript var radius = circle.radius; circle.setRadius(radius); circle.radius = radius; var iterations = circle.iterations; circle.iterations = iterations; ``` -------------------------------- ### Example Project Configuration Source: https://docs.phaser.io/phaser-editor/misc/project-config This JSON file configures project-specific settings for Phaser Editor, including resource filtering, custom plugins, server flags, and the URL for the play command. ```json { "skip": ["dist/", "editor-plugins/"], "settings": { "phasereditor2d.scene.enablePixelArt": true }, "plugins": [ "editor-plugins/my-fonts-plugins", "editor-plugins/my-awesome-plugins" ], "flags": ["-port", "7171"], "playUrl": "http://localhost:4200" } ``` -------------------------------- ### POST /loader/start Source: https://docs.phaser.io/phaser/concepts/loader Manually triggers the loader to begin downloading all queued assets. ```APIDOC ## POST /loader/start ### Description Starts the loading process for all assets currently in the queue. This is typically used when loading assets outside of the standard preload() method. ### Method POST ### Endpoint this.load.start() ### Parameters None ### Request Example {} ### Response #### Success Response (200) - **status** (string) - Loading process initiated. ``` -------------------------------- ### Getting Pointer Touch Start Time Source: https://docs.phaser.io/phaser/concepts/input This snippet retrieves the timestamp when the pointer initially went down. This is stored in 'downTime' and can be used for timing interactions. ```javascript pointer.downTime ``` -------------------------------- ### Manipulate Bob Properties Source: https://docs.phaser.io/phaser/concepts/gameobjects/blitter Examples of getting and setting properties for individual Bob objects, including position, frame, flip, visibility, alpha, and tint. ```javascript bob.setPosition(x, y); bob.setFrame(frame); bob.setFlip(boolX, boolY); bob.setVisible(boolean); bob.setAlpha(v); bob.setTint(tint); bob.destroy(); ``` -------------------------------- ### Control Phaser Timeline Playback Source: https://docs.phaser.io/phaser/concepts/time Provides examples for controlling the playback of a Phaser timeline, including starting, restarting, repeating infinitely or a specific amount, and stopping. ```javascript timeline.play(); // Start playback timeline.play(true); // Restart playback timeline.repeat().play(); // Repeat infinitely timeline.repeat(amount).play(); // Repeat a specific amount timeline.repeat(false); // Disable repeat timeline.stop(); // Stop playback ``` -------------------------------- ### Phaser Game Initialization with Callbacks Source: https://docs.phaser.io/phaser/concepts/game Illustrates initializing a Phaser Game with `preBoot` and `postBoot` callbacks. These functions allow for custom logic execution before and after the game systems are initialized, useful for setup and debugging. ```javascript const config = { preBoot: function (game) { console.log('game config', game.config); }, postBoot: function (game) { console.log('game canvas', game.canvas); } }; const game = new Phaser.Game(config); ``` -------------------------------- ### Create a Phaser 3 Hello World Application Source: https://docs.phaser.io/phaser/getting-started/set-up-dev-environment This snippet provides a complete HTML structure to initialize a Phaser 3 game. It includes loading external assets, configuring the game engine with arcade physics, and defining a basic scene with a moving logo and particle effect. ```html ``` -------------------------------- ### Getting Pointer Drag Start Coordinates Source: https://docs.phaser.io/phaser/concepts/input This snippet retrieves the X and Y coordinates where the pointer initially went down, marking the beginning of a drag operation. These are stored in 'downX' and 'downY'. ```javascript pointer.downX, pointer.downY ``` -------------------------------- ### Configure Scene Settings and Physics Source: https://docs.phaser.io/phaser/concepts/scenes Demonstrates how to pass a configuration object to the Scene constructor to set keys and physics engine parameters. ```javascript class Level1Scene extends Phaser.Scene { constructor () { super({ key: 'Level1', physics: { arcade: { debug: true, gravity: { y: 200 } } } }); } } ``` -------------------------------- ### Get Random Element from Array (JavaScript) Source: https://docs.phaser.io/phaser/concepts/utils Returns a random element from the provided array. It supports specifying a start index and the number of elements to choose from, defaulting to the entire array. ```javascript let array = [1, 2, 3, 4, 5]; let randomItem = Phaser.Utils.Array.GetRandom(array); console.log(randomItem); // Output: 2 let randomItem = Phaser.Utils.Array.GetRandom(array, 2, 2); // Consider elements from index 2 to index 3 console.log(randomItem); // Output: 3 or 4 ``` -------------------------------- ### Create Basic Phaser Game Instance Source: https://docs.phaser.io/phaser/concepts/game Demonstrates the fundamental way to create a Phaser Game instance with a simple scene. This is the starting point for any Phaser game, initializing the game engine and its core systems. ```javascript new Phaser.Game({ scene: { create: function () { this.add.text(0, 0, 'Hello world'); } } }); ``` -------------------------------- ### Phaser Tween Get Start/End Functions Source: https://docs.phaser.io/phaser/concepts/tweens Custom functions to define the start and end values for tween properties. 'getStart' modifies the initial value, and 'getEnd' modifies the final value. ```javascript getStart: function (target, key, value, targetIndex, totalTargets, tween) { return value + 30; }, getEnd: function (target, key, value, targetIndex, totalTargets, tween) { destX -= 30; return destX; } ``` -------------------------------- ### Retrieve Texture Keys and Instances Source: https://docs.phaser.io/phaser/concepts/textures Demonstrates how to fetch all available texture keys from the manager and how to safely retrieve a specific texture instance by verifying its existence first. ```javascript const keys = this.textures.getTextureKeys(); const texture = this.textures.exists("mummy") ? this.textures.get("mummy") : null; ``` -------------------------------- ### Get iOS Version in Phaser Source: https://docs.phaser.io/phaser/concepts/device Retrieves the major version number of iOS if the game is running on an Apple mobile device. This property is part of the Phaser.Device.OS object and requires no additional setup. ```javascript var version = scene.sys.game.device.os.iOSVersion; ``` -------------------------------- ### Get First Element in Array (JavaScript) Source: https://docs.phaser.io/phaser/concepts/utils Retrieves the first element in an array that matches specified criteria. It can filter by property and value, and allows for optional start and end indices. Returns null if no match is found. ```javascript var array = [ { name: "apple", color: "red" }, { name: "banana", color: "yellow" }, { name: "grape", color: "purple" }, { name: "strawberry", color: "red" }, { name: "squash", color: "yellow" }, { name: "eggplant", color: "purple" }, ]; var result = Phaser.Utils.Array.GetFirst(array, "color", "yellow"); console.log(result); // Output: { name: 'banana', color: 'yellow' } var result = Phaser.Utils.Array.GetFirst(array, "color"); console.log(result); // Output: { name: 'banana', color: 'yellow' } var result = Phaser.Utils.Array.GetFirst(array); console.log(result); // Output: { name: 'apple', color: 'red' } var result = Phaser.Utils.Array.GetFirst(array, "color", "purple", 3, 6); console.log(result); // Output: { name: 'eggplant', color: 'purple' } ``` -------------------------------- ### Create BitmapText Object Source: https://docs.phaser.io/phaser/concepts/gameobjects/bitmap-text Demonstrates how to instantiate a BitmapText object using the scene factory or a configuration object. ```javascript var txt = this.add.bitmapText(x, y, key, text); var txt = this.make.bitmapText({ x: 0, y: 0, text: 'Text\nGame Object\nCreated from config', font: '', size: false, align: 0, add: true }); ``` -------------------------------- ### Get Normalized Position from Distance on Curve Source: https://docs.phaser.io/phaser/concepts/math Calculates the normalized position 't' (0 to 1) along a curve corresponding to a given distance 'd' from the start. Note: This feature is not yet supported for Path objects. ```javascript var t = curve.getTFromDistance(d); ``` -------------------------------- ### Initialize Phaser Game with Scene Class Source: https://docs.phaser.io/phaser/concepts/scenes Demonstrates how to instantiate a Phaser game by passing a configuration object that includes a specific Scene class. ```javascript var config = { type: Phaser.AUTO, width: 800, height: 600, scene: MyScene }; var game = new Phaser.Game(config); ``` -------------------------------- ### Phaser Tween Stagger Configuration Examples Source: https://docs.phaser.io/phaser/concepts/tweens Demonstrates various ways to use the 'stagger' function in Phaser tweens for sequential animations. It covers different ranges, ease functions, start indices, and grid modes. ```javascript scene.tweens.stagger(endValue) scene.tweens.stagger([startValue, endValue]) scene.tweens.stagger(endValue, {ease: 'cubic.inout'}) scene.tweens.stagger([startValue, endValue], {ease: 'cubic.inout'}) scene.tweens.stagger(endValue, {from: 'last'}) scene.tweens.stagger(endValue, {from: 'center'}) scene.tweens.stagger(endValue, {from: index}) scene.tweens.stagger([startValue, endValue], {from: 'last'}) scene.tweens.stagger([startValue, endValue], {from: 'center'}) scene.tweens.stagger([startValue, endValue], {from: index}) scene.tweens.stagger(endValue, {from: 'last', ease: 'cubic.inout'}) scene.tweens.stagger([startValue, endValue], {from: 'last', ease: 'cubic.inout'}) scene.tweens.stagger(endValue, {grid: [gridWidth, gridHeight]}) scene.tweens.stagger(endValue, {grid: [gridWidth, gridHeight], from: 'center'}) scene.tweens.stagger(endValue, {grid: [gridWidth, gridHeight], from: 'center', ease: 'cubic.inout'}) scene.tweens.stagger([startValue, endValue], {grid: [gridWidth, gridHeight]}) scene.tweens.stagger([startValue, endValue], {grid: [gridWidth, gridHeight], from: 'center'}) scene.tweens.stagger([startValue, endValue], {grid: [gridWidth, gridHeight], from: 'center', ease: 'cubic.inout'}) ``` -------------------------------- ### Organize Game Object Creation without Class Extension Source: https://docs.phaser.io/phaser/concepts/gameobjects Demonstrates different approaches to organizing creation logic using helper functions or registering custom factory methods within the Phaser GameObjectFactory. ```javascript function create() { const mummy = createMummy.call(this, 0, 0); } function createMummy(x, y) { return this.add.mummy(x, y, 'mummy'); } ``` ```javascript function create() { const mummy = createMummy(this, 0, 0); } function createMummy(scene, x, y) { return scene.add.mummy(x, y, 'mummy'); } ``` ```javascript function create() { const mummy = this.add.mummy(0, 0); } Phaser.GameObjects.GameObjectFactory.register('mummy', function (x, y) { return this.sprite(x, y, 'mummy'); }); ``` -------------------------------- ### Phaser: Get Elapsed Time from Timer Source: https://docs.phaser.io/phaser/concepts/time Returns the total time that has passed since the timer was started or last reset, measured in milliseconds or seconds. This property is useful for tracking progress or determining how long an action has been active. ```javascript var elapsed = timer.getElapsed(); // ms var elapsed = timer.getElapsedSeconds(); // sec // var elapsed = timer.elapsed; // ms ``` -------------------------------- ### Create and Manage Phaser Containers Source: https://docs.phaser.io/phaser/concepts/gameobjects/container Demonstrates how to instantiate a basic container, create a custom container class by extending the base class, and destroy containers along with their children. ```javascript var container = this.add.container(x, y); class MyContainer extends Phaser.GameObjects.Container { constructor(scene, x, y, children) { super(scene, x, y, children); this.add.existing(this); } } var customContainer = new MyContainer(scene, x, y, children); container.destroy(); ``` -------------------------------- ### Shader Loading and Instantiation Source: https://docs.phaser.io/phaser/concepts/gameobjects/shader Basic methods for loading GLSL files and adding shader instances to the Phaser display list. ```javascript this.load.glsl(key, url); var shader = this.add.shader(key, x, y, width, height, textures); ``` -------------------------------- ### Getting Pointer Position in World Coordinates (Single Camera) Source: https://docs.phaser.io/phaser/concepts/input This example shows how to convert the pointer's screen coordinates to world coordinates using its associated camera. This is essential for game logic that interacts with the game world rather than just the screen. ```javascript var worldX = pointer.worldX; var worldY = pointer.worldY; ``` -------------------------------- ### Control Phaser Sound Manager Mute Source: https://docs.phaser.io/phaser/concepts/audio Provides examples for setting and getting the mute state of the Phaser Sound Manager. The `setMute` method takes a boolean value, and the `mute` property can be directly accessed to retrieve the current mute status. ```javascript this.sound.setMute(mute); // mute: true/false // this.sound.mute = mute; var mute = this.sound.mute; ``` -------------------------------- ### Load Extra Plugins with Command Line Source: https://docs.phaser.io/phaser-editor/misc/plugins Use the `-plugins` flag with a semicolon-separated string of absolute paths to load additional plugins when starting Phaser Editor Core. ```bash $ PhaserEditor -plugins "/demo/plugins;/some/extra/plugins" -project . ``` -------------------------------- ### Get Animation Properties of Phaser Mesh Source: https://docs.phaser.io/phaser/concepts/gameobjects/mesh Retrieves various properties of the current animation applied to a Phaser Mesh object. This includes checking if the animation has started, is playing, or is paused, as well as accessing frame counts, delays, repeat settings, and current animation details. These properties are read-only or accessed via getter methods. ```javascript var hasStarted = plane.anims.hasStarted; var isPlaying = plane.anims.isPlaying; var isPaused = plane.anims.isPaused; var frameCount = plane.anims.getTotalFrames(); var delay = plane.anims.delay; var repeatCount = plane.anims.repeat; var repeatCounter = plane.anims.repeatCounter; var repeatDelay = plane.anims.repeatDelay; var yoyo = plane.anims.yoyo; var key = plane.anims.getName(); var frameName = plane.anims.getFrameName(); var currentAnim = plane.anims.currentAnim; var currentFrame = plane.anims.currentFrame; ``` -------------------------------- ### Install Linux Shortcuts Source: https://docs.phaser.io/phaser-editor/first-steps/download-and-install Use the install.sh script to create desktop shortcuts and menu entries for Phaser Editor on Linux. The uninstall.sh script can be used to remove them. ```bash $ ./install.sh ``` ```bash $ ./uninstall.sh ``` -------------------------------- ### Configure Server Options in flags.txt Source: https://docs.phaser.io/phaser-editor/misc/server-options Define server options in the `flags.txt` file for persistent configuration. Each line represents a command-line argument. ```plaintext -public -port 80 ``` -------------------------------- ### Create and Play Phaser Audio Sprite Instance Source: https://docs.phaser.io/phaser/concepts/audio This code shows how to create a sound instance from an audio sprite key, optionally with a configuration object. It then demonstrates playing a specific marker from this instance, with an optional config to override settings. ```javascript var music = this.sound.addAudioSprite(key, config); music.play(markerName); music.play(markerName, config); ``` -------------------------------- ### Emitter Start Event - JavaScript Source: https://docs.phaser.io/phaser/concepts/gameobjects/particles Listens for the 'start' event, which is emitted when the particle emission begins. ```javascript emitter.on('start', function(emitter) { }) ``` -------------------------------- ### Project Structure for Asset Packs Source: https://docs.phaser.io/phaser-editor/asset-pack-editor/organizing-the-assets This example illustrates a recommended project structure for organizing multiple Asset Pack files based on their purpose, such as preloader, levels, and helper assets. This organization helps the Asset Pack Editor function more effectively. ```text assets/ preload/ preload-pack.json ... # preloader assets levels/ levels-pack.json ... # level assets helpers/ helper-pack.json ... # helper assets ``` -------------------------------- ### Install Spine Phaser via NPM Source: https://docs.phaser.io/phaser-editor/scene-editor/spine-animations/spine-animations-install Use this command to install the Spine Phaser runtime as a dependency in your project. ```bash npm install @esotericsoftware/spine-phaser ``` -------------------------------- ### Instantiate and Configure HorizontalMove Component Source: https://docs.phaser.io/phaser-editor/scene-editor/user-components/user-components-compiler Shows how to create an instance of the HorizontalMove component and set its properties after initialization. ```javascript const enemy = this.add.image(...); const enemyMove = new HorizontalMove(enemyMove); enemyMove.maxX = 400; ``` -------------------------------- ### Install Phaser via NPM Source: https://docs.phaser.io/phaser/getting-started/installation Install the Phaser package as a dependency in your existing project using the Node Package Manager. ```bash npm install phaser ``` -------------------------------- ### Install Phaser Editor Plugin via NPM Source: https://docs.phaser.io/phaser-editor/misc/plugins Install third-party plugins like `phasereditor2d-ninepatch-plugin` as development dependencies using npm. ```bash $ npm install phasereditor2d-ninepatch-plugin --save-dev ``` -------------------------------- ### Loading Assets in Preload and Manual Stages Source: https://docs.phaser.io/phaser/concepts/loader Demonstrates how to add image assets to the loader during the preload stage and how to manually trigger loading outside of the preload function using completion callbacks. ```javascript this.load.image(key, url); this.load.once("complete", callback, scope); this.load.start(); ``` ```javascript this.load .image(["conch", "treasure", "trident"]) .once("complete", () => { // All files complete }) .start(); ``` -------------------------------- ### Project Structure for Asset Packs Source: https://docs.phaser.io/phaser-editor/v4/asset-pack-editor/organizing-the-assets This example illustrates a recommended project directory structure for organizing multiple Asset Pack JSON files and their associated assets. It separates assets by their purpose, such as preloading, levels, and helper assets. ```plaintext assets/ preload/ preload-pack.json ... # preloader assets levels/ levels-pack.json ... # level assets helpers/ helper-pack.json ... # helper assets ``` -------------------------------- ### Get Frame from Animation Source: https://docs.phaser.io/phaser/concepts/animations Retrieves a specific frame from an animation by its index, checks for the existence of a frame at an index, or gets the last frame. ```javascript var HasFrameAt = anim.checkFrame(index); var frame = anim.getFrameAt(index); var frame = anim.getLastFrame(); const mummyWalkFrame1 = this.anims.get("mummyWalk").getFrameAt(1); ``` -------------------------------- ### Create and Customize Grid Source: https://docs.phaser.io/phaser/concepts/gameobjects/graphics Demonstrates how to create a grid shape and how to extend the Grid class for custom behavior. ```javascript var grid = this.add.grid(x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha); class MyGrid extends Phaser.GameObjects.Grid { constructor(scene, x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha) { super(scene, x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha); this.add.existing(this); } } ``` -------------------------------- ### RotateObject Component Example Source: https://docs.phaser.io/phaser-editor/scene-editor/user-components/user-components-super-class An example of a derived component, RotateObject, that extends UserComponent and implements the update method to rotate the game object. ```javascript class RotateObject extends UserComponent { constructor(gameObject) { super(gameObject); } ... update() { // this method is called when the scene // emits the UPDATE event this.gameObject.angle += 1; } } ``` -------------------------------- ### Dump All Scenes After Game Boot Source: https://docs.phaser.io/phaser/concepts/scenes Demonstrates how to use `game.scene.dump()` within the `callbacks.postBoot` function to log all currently loaded scenes to the console. ```javascript new Phaser.Game({ scene: [ /* etc. */ ], callbacks: { postBoot: function (game) { game.scene.dump(); // Look for output in console. }, }, }); ``` -------------------------------- ### Configure Server Options in flags.txt Source: https://docs.phaser.io/phaser-editor/v4/misc/server-options The `flags.txt` file allows pre-configuring server options. Each line in the file represents a command-line argument. Blank lines and lines starting with '#' are ignored. ```bash -public -port 80 ``` ```bash -public # -port # 80 ``` -------------------------------- ### Configure Arcade Physics in Phaser Game Source: https://docs.phaser.io/phaser/concepts/physics/arcade Demonstrates how to initialize the Arcade Physics system within the global Phaser Game configuration object. This includes both basic setup and advanced property customization like gravity and debug visualization. ```javascript const config = { physics: { default: 'arcade' } }; const game = new Phaser.Game(config); ``` ```javascript const config = { physics: { default: "arcade", arcade: { gravity: { x: 0, y: 0 }, debug: false, fps: 60 } } }; const game = new Phaser.Game(config); ``` -------------------------------- ### Prefab Instance in a Scene Source: https://docs.phaser.io/phaser-editor/scene-editor/prefabs/prefab-code This example demonstrates how a Prefab instance is created and added to a scene when a regular scene file is compiled. It shows instantiation, adding to the display list, and modifying properties. ```javascript class Level extends Phaser.Scene { constructor() { super("Level"); } create() { ... // create the instance of the Dragon prefab class const dragon = new Dragon(this, 190, 120); // add the instance to the display list this.add.existing(dragon); // modify the 'angle' property of the instance dragon.angle = -30; ... } } ``` -------------------------------- ### macOS Custom Code Editor Path Example Source: https://docs.phaser.io/phaser-editor/workbench/settings Example of a macOS path for the Visual Studio Code executable. Paths with spaces must be quoted. ```text "/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code" ``` -------------------------------- ### HorizontalMove Component Example Source: https://docs.phaser.io/phaser-editor/scene-editor/user-components/user-components-start-update-methods An example of a derived component that overrides the update method to provide continuous horizontal movement for a game object. This demonstrates how to extend the EventComponent. ```javascript class HorizontalMove extends EventComponent { ... update() { this.gameObject.x += this.deltaX; } } ``` -------------------------------- ### Get Image Texture - Phaser IO Source: https://docs.phaser.io/phaser/concepts/textures Retrieves an image texture from the Texture Manager using its key. It also shows how to get the source image object from the texture. ```javascript var texture = this.textures.get(key); var image = texture.getSourceImage(); ``` -------------------------------- ### Timeline Creation and Configuration Source: https://docs.phaser.io/phaser/concepts/time Demonstrates how to create a new timeline and configure its events with various conditions and actions. ```APIDOC ## Create timeline ### Description Creates a new timeline instance with a configuration array of events. ### Method `Phaser.GameObjects.GameObject.add.timeline` ### Endpoint N/A (This is a constructor/factory method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **config** (array) - Required - An array of event configurations. - **at** (number) - Optional - Absolute delay time in ms. - **in** (number) - Optional - Absolute delay time after current time in ms. - **from** (number) - Optional - Relative delay time after previous event in ms. - **if** (function) - Optional - A function that returns true to enable the event. - **set** (object) - Optional - Key-value pairs of properties to set on the target. - **tween** (object) - Optional - Tween configuration object. - **run** (function) - Optional - A function to execute when the event fires. - **loop** (function) - Optional - A function to execute when the event sequence repeats. - **sound** (string|object) - Optional - Key of a sound to play or a sound configuration object. - **event** (string) - Optional - Event name to emit from the Timeline instance. - **target** (object) - Optional - The scope for the `run` function. - **once** (boolean) - Optional - If true, the event is removed after firing. - **stop** (boolean) - Optional - If true, the timeline stops when this event fires. ### Request Example ```javascript var timeline = this.add.timeline([ { at: 0, run: function() { console.log('Event fired!'); }, tween: { targets: gameObject, alpha: 1, duration: 1000 } } ]); ``` ### Response #### Success Response (200) - **timeline** (Phaser.Time.Timeline) - The created timeline instance. #### Response Example ```json { "timeline": "[Phaser.Time.Timeline object]" } ``` ``` -------------------------------- ### Phaser Event Emitter - Getting Listeners (JavaScript) Source: https://docs.phaser.io/phaser/concepts/events Demonstrates how to get an array of all listeners currently attached to a specific event. This can be helpful for debugging or inspecting event handlers. ```javascript var listeners = ee.listeners(eventName); ``` -------------------------------- ### Configure Multiple Scenes in Game Config Source: https://docs.phaser.io/phaser/concepts/scenes Shows how to define multiple scenes using configuration objects within the main game configuration. Scenes marked with `{ active: true }` will start automatically. ```javascript const bootSceneConfig = { key: 'boot', /*...*/ }; const playSceneConfig = { key: 'play', /*...*/ }; const uiSceneConfig = { key: 'ui', active: true }; new Phaser.Game({ // 'boot' and 'ui' will be started scene: [ bootSceneConfig, playSceneConfig, uiSceneConfig ] }; ``` -------------------------------- ### Create and Listen for Keyboard Combos in Phaser Source: https://docs.phaser.io/phaser/concepts/input Demonstrates how to create a sequence of key presses (a combo) and listen for its completion. Supports various input formats for keys and offers options to control combo behavior like resetting or deleting on match. Dependencies include the Phaser input manager. ```javascript var keyCombo = scene.input.keyboard.createCombo(keys, { // resetOnWrongKey: true, // maxKeyDelay: 0, // resetOnMatch: false, // deleteOnMatch: false, }); ``` ```javascript scene.input.keyboard.on("keycombomatch", function (keyCombo, keyboardEvent) { /* ... */ }); ``` -------------------------------- ### Texture Config Property Example (Atlas Frame) Source: https://docs.phaser.io/phaser-editor/scene-editor/prefabs/prefab-user-properties Represents a texture selected from an Asset Pack. This example shows the configuration for a specific frame within an atlas texture. ```json { "key": "atlas-props", "frame": "branch-01" } ``` -------------------------------- ### Get Transformed Corners in World Coordinates (Phaser) Source: https://docs.phaser.io/phaser/concepts/gameobjects Shows how to get the world coordinates of the eight key points (corners and edge centers) of a game object after all its transformations have been applied. ```javascript const { x, y } = gameObject.getTopLeft(undefined, true); const { x, y } = gameObject.getTopCenter(undefined, true); const { x, y } = gameObject.getTopRight(undefined, true); const { x, y } = gameObject.getLeftCenter(undefined, true); const { x, y } = gameObject.getRightCenter(undefined, true); const { x, y } = gameObject.getBottomLeft(undefined, true); const { x, y } = gameObject.getBottomCenter(undefined, true); const { x, y } = gameObject.getBottomRight(undefined, true); ``` -------------------------------- ### Scene Configuration with Key and Physics Source: https://docs.phaser.io/phaser/concepts/scenes This snippet demonstrates how to configure a Scene class by passing a configuration object to the super constructor. This object can define properties like the scene's key and physics settings. ```APIDOC ## Scene Configuration with Key and Physics ### Description This example shows how to define settings for a Phaser Scene when it is created. The `super()` call within the Scene's constructor accepts a configuration object that can set the scene's unique key and configure the physics engine. ### Method Scene constructor ### Endpoint N/A ### Parameters #### Request Body - **config** (object) - Optional - Configuration object for the Scene. - **key** (string) - Required - The unique key for this Scene. - **physics** (object) - Optional - Physics configuration. - **arcade** (object) - Optional - Arcade physics configuration. - **debug** (boolean) - Optional - Enable debug drawing for physics. - **gravity** (object) - Optional - Set gravity for the physics world. - **y** (number) - Optional - Gravity force on the Y-axis. ### Request Example ```javascript class Level1Scene extends Phaser.Scene { constructor () { super({ key: 'Level1', physics: { arcade: { debug: true, gravity: { y: 200 } } } }); } } ``` ### Response #### Success Response (200) N/A (Scene setup) #### Response Example N/A ``` -------------------------------- ### Layer Creation Source: https://docs.phaser.io/phaser/concepts/gameobjects/layer Demonstrates how to create a new Layer, optionally with initial children. ```APIDOC ## Create Layer ### Description Creates a new Layer instance. A Layer is a special type of Game Object that acts as a Display List, allowing you to group and manage multiple Game Objects. ### Method `this.add.layer()` ### Endpoint N/A (Phaser Scene method) ### Parameters #### Query Parameters - **children** (array) - Optional - An array of game objects to be added to the layer upon creation. ### Request Example ```javascript // Create an empty layer var layer = this.add.layer(); // Create a layer with initial children var layerWithChildren = this.add.layer([ sprite1, sprite2 ]); ``` ### Response #### Success Response (200) - **Layer** (object) - The newly created Layer instance. #### Response Example ```json { "layerInstance": "[Phaser.GameObjects.Layer]" } ``` ``` -------------------------------- ### Set and Get Collision Category Source: https://docs.phaser.io/phaser/concepts/physics/arcade Manages the collision category for the game object's body, which determines its interaction with other physics bodies. You can set, get, or reset the category using bitmasks. ```javascript var collisionCategory = gameObject.body.collisionCategory; gameObject.setCollisionCategory(category); gameObject.resetCollisionCategory(); ``` -------------------------------- ### Remove Elements Between Indices in Phaser Array Source: https://docs.phaser.io/phaser/concepts/utils Removes a range of elements from an array, specified by a start and end index (inclusive of start, exclusive of end). Callbacks can be used to process removed items. ```javascript let array = [1, 2, 3, 4, 5]; Phaser.Utils.Array.RemoveBetween(array, 1, 3); console.log(array); // [1, 4, 5] ``` -------------------------------- ### Phaser.Display.BaseShader Constructor Source: https://docs.phaser.io/phaser/concepts/gameobjects/shader Demonstrates the creation of a new BaseShader instance with its key, fragment source, vertex source, and optional uniforms. ```APIDOC ## BaseShader Constructor ### Description Creates a new BaseShader instance. ### Method `new Phaser.Display.BaseShader(key, fragmentSrc, vertexSrc, uniforms)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (string) - Required - The key of this shader. - **fragmentSrc** (string) - Required - The fragment source for the shader. - **vertexSrc** (string) - Optional - The vertex source for the shader. If undefined or empty, the default vertex source is used. - **uniforms** (object) - Optional - An object defining the uniforms the shader uses. Each uniform should be an object with `type` and `value` properties. - **uniformName** (string) - The name of the uniform as used in the fragment source. - **type** (string) - The type of the uniform. Supported types include: - `'1f'` (float): `value` is a single float. Example: `{ type: '1f', value: 0 }` - `'2f'` (vec2): `value` is an object with `{x, y}` float numbers. Example: `{ type: '2f', value: { x: 100, y: 200 } }` - `'3f'` (vec3): `value` is an object with `{x, y, z}` float numbers. Example: `{ type: '3f', value: { x: 1, y: 0, z: 0 } }` - `'4f'` (vec4): `value` is an object with `{x, y, z, w}` float numbers. ### Request Example ```javascript var fragmentShaderSource = "precision mediump float;\nuniform sampler2D uMainSampler;\nvary vec2 outTexCoord;\nvoid main() {\n vec4 color = texture2D(uMainSampler, outTexCoord);\n gl_FragColor = color;\n}"; var vertexShaderSource = "precision mediump float;\nattribute vec2 inPosition;\nattribute vec2 inTexCoord;\nuniform mat4 uProjectionMatrix;\nvary vec2 outTexCoord;\nvoid main() {\n outTexCoord = inTexCoord;\n gl_Position = uProjectionMatrix * vec4(inPosition, 1.0, 1.0);\n}"; var uniforms = { time: { type: '1f', value: 0.0 }, resolution: { type: '2f', value: { x: 800, y: 600 } } }; var baseShader = new Phaser.Display.BaseShader('myShaderKey', fragmentShaderSource, vertexShaderSource, uniforms); ``` ### Response #### Success Response (200) N/A (This is a constructor, it returns an instance of BaseShader) #### Response Example ```javascript // Returns a Phaser.Display.BaseShader instance ``` ``` -------------------------------- ### Phaser Circle Properties: Get and Set Display Size Source: https://docs.phaser.io/phaser/concepts/gameobjects/graphics Illustrates how to get and set the display width and height of a Phaser Circle object. This allows for scaling the circle's visual representation. ```javascript var width = circle.displayWidth; var height = circle.displayHeight; circle.setDisplaySize(width, height); circle.displayWidth = width; circle.displayHeight = height; ``` -------------------------------- ### Group Creation Source: https://docs.phaser.io/phaser/concepts/gameobjects/group Demonstrates how to create a new Group instance, optionally with initial game objects and configuration. ```APIDOC ## Add group object ### Description Creates a new Group. ### Method `this.add.group(config)` or `this.add.group(gameObjects, config)` ### Parameters * `config` (object) - Optional configuration object for the group. * `classType` (Phaser.GameObjects.GameObject) - The class type of the game objects to be created in the group (e.g., `Phaser.GameObjects.Sprite`, `Phaser.GameObjects.Image`). Defaults to `Phaser.GameObjects.GameObject`. * `defaultKey` (string) - The texture key to use when creating new game objects if not specified. * `defaultFrame` (string|integer) - The frame to use when creating new game objects if not specified. * `active` (boolean) - Whether the group should be active. * `maxSize` (integer) - The maximum number of children the group can hold. `-1` means no limit. * `runChildUpdate` (boolean) - If `true`, the `update()` method of each child game object will be called every tick. * `createCallback` (function) - A callback function to be invoked when a new child is added or created. * `removeCallback` (function) - A callback function to be invoked when a child is removed. * `createMultipleCallback` (function) - A callback function to be invoked when multiple children are created at once. * `gameObjects` (array) - An optional array of existing Game Objects to add to the group upon creation. ### Request Example ```javascript // Create a group of Sprites with default configuration var group = this.add.group(); // Create a group with specific configuration var config = { classType: Phaser.GameObjects.Image, maxSize: 10 }; var group = this.add.group(config); // Create a group and add existing game objects var sprite1 = this.add.sprite(100, 100, 'button'); var sprite2 = this.add.sprite(200, 200, 'button'); var group = this.add.group([sprite1, sprite2]); ``` ``` -------------------------------- ### Quick Play Project Command Source: https://docs.phaser.io/phaser-editor/v4/workbench/playing-project To run the game directly within the editor in an internal window, use the 'Quick Play Project' command or press F10. This bypasses the system browser for a more integrated development experience. ```text Quick Play Project command or F10 ``` -------------------------------- ### Place Game Objects on a Rectangle Source: https://docs.phaser.io/phaser/concepts/actions Positions an array of Game Objects evenly around the perimeter of a Phaser.Geom.Rectangle. The placement starts at the top-left and proceeds clockwise, with an optional shift parameter to offset the starting position. ```javascript const rect = new Phaser.Geom.Rectangle(100, 100, 600, 400); Phaser.Actions.PlaceOnRectangle(myObjects, rect); ``` -------------------------------- ### Phaser Curve Properties: Get and Set Fill Style Source: https://docs.phaser.io/phaser/concepts/gameobjects/graphics Illustrates how to get and set the fill color and alpha of a Phaser Curve object using `setFillStyle`. It also shows how to clear the fill style. ```javascript var color = curve.fillColor; var alpha = curve.fillAlpha; curve.setFillStyle(color, alpha); curve.setFillStyle(); ``` -------------------------------- ### Initialize Phaser Game with Scene Object Source: https://docs.phaser.io/phaser/concepts/scenes Shows how to define a scene using a plain object containing lifecycle methods like preload and create, which the Scene Manager automatically processes. ```javascript var config = { type: Phaser.AUTO, width: 800, height: 600, scene: { preload: preload, create: create } }; var game = new Phaser.Game(config); function preload () { this.load.image('logo', 'assets/sprites/logo.png'); } function create () { this.add.image(400, 300, 'logo'); } ``` -------------------------------- ### Initialize and Add Mesh Object Source: https://docs.phaser.io/phaser/concepts/gameobjects/mesh Demonstrates how to load a texture and instantiate a Mesh object using either the scene's add or make factory methods. ```javascript this.load.image(key, url); var mesh = this.add.mesh(x, y, texture, frame); var mesh = this.make.mesh({ x: 0, y: 0, add: true, key: null, frame: null }); ```