### Quick Start: Create and Follow a Path Source: https://github.com/phaserjs/phaser/blob/master/skills/curves-and-paths/SKILL.md Basic setup showing how to create a Path, add curves, draw it with Graphics, and attach a PathFollower sprite that moves along the path with rotation and repeat options. ```javascript // In a Scene's create() method: // 1. Create a Path starting at (50, 300) const path = this.add.path(50, 300); // 2. Add curves to the path path.lineTo(200, 100); path.splineTo([ new Phaser.Math.Vector2(300, 400), new Phaser.Math.Vector2(500, 200) ]); path.lineTo(700, 300); // 3. Draw the path using Graphics const graphics = this.add.graphics(); graphics.lineStyle(2, 0xffffff, 1); path.draw(graphics, 64); // 4. Create a PathFollower sprite that moves along the path const follower = this.add.follower(path, 50, 300, 'ship'); follower.startFollow({ duration: 5000, rotateToPath: true, repeat: -1, yoyo: true }); ``` -------------------------------- ### Phaser 4 Matter.js Quick Start Example Source: https://github.com/phaserjs/phaser/blob/master/skills/physics-matter/SKILL.md This example demonstrates how to set up a basic Phaser 4 game with Matter.js physics, including creating dynamic sprites and images, a static rectangle body, and enabling pointer dragging. It also shows how to configure Matter physics in the game configuration and handle player input for movement. ```js class GameScene extends Phaser.Scene { create() { // Matter sprite (dynamic, has animation support) this.player = this.matter.add.sprite(400, 200, 'player'); this.player.setBounce(0.5); this.player.setFriction(0.05); // Matter image (dynamic, no animation) const box = this.matter.add.image(300, 100, 'crate'); // Static body from raw shape this.matter.add.rectangle(400, 580, 800, 40, { isStatic: true }); // Enable pointer dragging on all bodies this.matter.add.mouseSpring(); this.cursors = this.input.keyboard.createCursorKeys(); } update() { if (this.cursors.left.isDown) { this.player.setVelocityX(-5); } else if (this.cursors.right.isDown) { this.player.setVelocityX(5); } if (this.cursors.up.isDown && this.player.body.velocity.y > -0.1) { this.player.setVelocityY(-10); } } } // Enable Matter physics in game config const config = { type: Phaser.AUTO, width: 800, height: 600, physics: { default: 'matter', matter: { gravity: { y: 1 }, enableSleeping: true, debug: true, setBounds: true // walls around canvas edges } }, scene: GameScene }; const game = new Phaser.Game(config); ``` -------------------------------- ### Creating Matter Game Objects Examples Source: https://github.com/phaserjs/phaser/blob/master/skills/physics-matter/SKILL.md Practical examples demonstrating how to instantiate Matter Sprites and Images, apply custom body shapes, integrate PhysicsEditor data, and add Matter physics to existing Phaser Game Objects. ```APIDOC ## Creating Matter Sprites and Images ### Example: Default Rectangle Body ```js const player = this.matter.add.sprite(200, 300, 'hero'); // default rect body matching texture ``` ### Example: Custom Body Shapes ```js // Circle shape const ball = this.matter.add.image(400, 100, 'ball', null, { shape: { type: 'circle', radius: 24 } }); // Polygon shape const hex = this.matter.add.sprite(300, 100, 'hex', null, { shape: { type: 'polygon', sides: 6, radius: 32 } }); // Custom vertices shape const ship = this.matter.add.sprite(400, 200, 'ship', null, { shape: { type: 'fromVerts', verts: '0 0 40 0 40 40 20 60 0 40' } }); ``` ### Example: PhysicsEditor Shape Data ```js // Load shapes from JSON cache const shapes = this.cache.json.get('shapes'); const enemy = this.matter.add.sprite(500, 200, 'enemy', null, { shape: shapes.enemy }); ``` ### Example: Adding Matter Physics to Existing Game Object ```js const existingSprite = this.add.sprite(100, 100, 'box'); this.matter.add.gameObject(existingSprite, { restitution: 0.8 }); // existingSprite now has setVelocity, setBounce, etc. ``` ``` -------------------------------- ### Complete Example: Dungeon Scene with Cone Light Source: https://github.com/phaserjs/phaser/blob/master/docs/Phaser 4 Cone Lights/Phaser 4 Cone Lights.md This example demonstrates setting up a Phaser 4 scene with a player character and a cone light that follows the player. It includes preloading assets, enabling lighting, adding images and sprites with lighting enabled, creating a cone light, and handling player movement to update the light's position and rotation. ```javascript class DungeonScene extends Phaser.Scene { preload () { this.load.image('floor', 'assets/floor.png'); this.load.image('floor_n', 'assets/floor_n.png'); this.load.image('player', 'assets/player.png'); this.load.image('player_n', 'assets/player_n.png'); } create () { this.lights.enable(); this.lights.setAmbientColor(0x050505); const floor = this.add.image(400, 300, 'floor'); floor.setLighting(true); this.player = this.add.sprite(400, 300, 'player'); this.player.setLighting(true); this.lantern = this.lights.addConeLight( this.player.x, this.player.y, 420, 0xffcc88, 2.2, 0, Phaser.Math.DegToRad(55), Phaser.Math.DegToRad(110), 42 ); this.cursors = this.input.keyboard.createCursorKeys(); } update () { const speed = 3; if (this.cursors.left.isDown) { this.player.x -= speed; this.player.rotation = Math.PI; } else if (this.cursors.right.isDown) { this.player.x += speed; this.player.rotation = 0; } if (this.cursors.up.isDown) { this.player.y -= speed; this.player.rotation = -Math.PI / 2; } else if (this.cursors.down.isDown) { this.player.y += speed; this.player.rotation = Math.PI / 2; } this.lantern.x = this.player.x; this.lantern.y = this.player.y; this.lantern.setConeRotation(this.player.rotation); } } ``` -------------------------------- ### Install Phaser via npm Source: https://github.com/phaserjs/phaser/blob/master/README.md Use this command to install the Phaser framework using npm. Then, import it into your project using the provided JavaScript statement. ```bash npm install phaser ``` ```javascript import Phaser from 'phaser'; ``` -------------------------------- ### Initialize Groups, Containers, and Layers Source: https://github.com/phaserjs/phaser/blob/master/skills/groups-and-containers/SKILL.md Basic setup for logical grouping, visual parent-child relationships with inherited transforms, and render-order buckets. ```javascript // In a Scene's create() method: // --- Group: logical collection, no transform, great for pooling --- const enemies = this.add.group(); enemies.create(100, 200, 'enemy'); // creates Sprite at (100,200) enemies.create(300, 200, 'enemy'); // --- Container: visual parent with inherited transform --- const hud = this.add.container(10, 10); const icon = this.add.image(0, 0, 'heart'); const label = this.add.text(20, 0, 'x3'); hud.add([icon, label]); // children move/scale/rotate with hud // --- Layer: render-ordering bucket, no position/scale --- const bgLayer = this.add.layer(); const fgLayer = this.add.layer(); bgLayer.add(this.add.image(400, 300, 'sky')); fgLayer.add(this.add.sprite(400, 300, 'player')); ``` -------------------------------- ### Quick Start: DataManager Usage Across Scopes Source: https://github.com/phaserjs/phaser/blob/master/skills/data-manager/SKILL.md This snippet demonstrates basic usage of DataManager for GameObjects, Scene data, and the global Registry. It covers setting, getting, incrementing, and toggling data values. ```js // Per-GameObject data (auto-creates DataManager on first use) const gem = this.add.sprite(100, 100, 'gem'); gem.setData('value', 50); gem.setData({ color: 'red', level: 2 }); gem.getData('value'); // 50 gem.getData(['value', 'color']); // [50, 'red'] // Increment / toggle helpers gem.incData('value', 10); // value is now 60 gem.incData('value', -5); // value is now 55 (negative to decrement) gem.toggleData('active'); // false -> true (starts from false if unset) // Scene-level data (this.data is a DataManagerPlugin) this.data.set('score', 0); this.data.get('score'); // 0 this.data.values.score += 100; // triggers changedata event // Global registry (shared across ALL scenes) this.registry.set('highScore', 9999); // Any scene can read it: this.registry.get('highScore'); // 9999 ``` -------------------------------- ### Extension Index Mapping Examples Source: https://github.com/phaserjs/phaser/blob/master/docs/Phaser Compact Texture Atlas Format Specification/Phaser Compact Texture Atlas Format Specification.md Demonstrates how hardcoded indices map to specific file extensions or how raw extensions are preserved. ```text sword~1 → "sword.png" frame1~3 → "frame1.jpg" 0/idle_01~2 → folder[0] + "/idle_01.webp" heightmap.tga → "heightmap.tga" (unknown ext stored raw) ``` -------------------------------- ### Start Game States Source: https://github.com/phaserjs/phaser/wiki/Phaser-General-Documentation-:-States Trigger a registered state using its unique key. The last started state becomes the current game state. ```javascript game.state.start(key); ``` ```javascript pacman.state.start('firstState'); ``` -------------------------------- ### Combined Range and Extension Syntax Source: https://github.com/phaserjs/phaser/blob/master/docs/Phaser Compact Texture Atlas Format Specification/Phaser Compact Texture Atlas Format Specification.md Example of a fully composed string including folder index, range expansion, and a trailing extension suffix. ```text 0/frame#1-23~1 ``` ```text 0/frame#1-23~1 ``` -------------------------------- ### Loading Images, Spritesheets, and SVGs Source: https://github.com/phaserjs/phaser/blob/master/skills/loading-assets/SKILL.md Examples for loading standard images, normal maps, fixed-frame spritesheets, and rasterized SVGs. ```javascript preload() { // Single image this.load.image('star', 'assets/star.png'); // Image with normal map (pass URL array: [texture, normalMap]) this.load.image('brick', ['assets/brick.png', 'assets/brick_n.png']); // Sprite sheet (fixed frame sizes) this.load.spritesheet('explosion', 'assets/explosion.png', { frameWidth: 64, frameHeight: 64, startFrame: 0, endFrame: 23, margin: 0, spacing: 0 }); // SVG (optionally rasterize at a specific size) this.load.svg('logo', 'assets/logo.svg', { width: 400, height: 400 }); } ``` -------------------------------- ### Atlas Example: Minimal Configuration Source: https://github.com/phaserjs/phaser/blob/master/docs/Phaser Compact Texture Atlas Format Specification/Phaser Compact Texture Atlas Format Specification.md Shows a minimal atlas definition with a single untrimmed sprite, no folders, and no blocks. ```text PCT:1.0 P:atlas_0.png,RGBA8888,256,256,1 logo|0|1,1,200,180 ``` -------------------------------- ### Load and play Video game object Source: https://github.com/phaserjs/phaser/blob/master/skills/sprites-and-images/SKILL.md Load a video file in preload and create a video game object with position and scale support. Call play() to start playback. ```javascript // Load in preload: this.load.video('intro', 'intro.mp4'); // Create in create: const video = this.add.video(400, 300, 'intro'); video.play(); ``` -------------------------------- ### Method `get(key)` Source: https://github.com/phaserjs/phaser/blob/master/skills/animations/SKILL.md Get a local animation by key ```APIDOC ## get sprite.anims.get ### Description Get a local animation by its key from this sprite. ### Method get ### Endpoint sprite.anims.get ### Parameters #### Request Body - **key** (string) - Required - The key of the animation to retrieve. ### Request Example ```json { "key": "local_anim" } ``` ### Response #### Success Response (200) - **animation** (object) - The animation object, or null if not found. #### Response Example ```json { "animation": { "key": "local_anim", "frameRate": 10 } } ``` ``` -------------------------------- ### Create a Basic Phaser Game with Scene Source: https://github.com/phaserjs/phaser/blob/master/skills/game-setup-and-config/SKILL.md Minimal setup with a single scene and default 1024×768 canvas. Triggers the full boot sequence including config parsing, renderer creation, DOM insertion, and game loop initialization. ```javascript class MyScene extends Phaser.Scene { preload() { this.load.image('logo', 'assets/logo.png'); } create() { this.add.image(400, 300, 'logo'); } } const config = { type: Phaser.AUTO, scene: MyScene }; const game = new Phaser.Game(config); ``` -------------------------------- ### Phaser 4 Quick Start: Text, BitmapText, and DynamicBitmapText Source: https://github.com/phaserjs/phaser/blob/master/skills/text-and-bitmaptext/SKILL.md Initialize different text types for common use cases. Remember to load bitmap fonts before using BitmapText or DynamicBitmapText. ```js // Canvas-based Text (flexible styling, uses browser fonts) const title = this.add.text(400, 50, 'Hello World', { fontFamily: 'Arial', fontSize: '32px', color: '#ffffff' }); // BitmapText (pre-rendered font texture, faster rendering) // Font must be loaded first: this.load.bitmapFont('myFont', 'font.png', 'font.xml') const score = this.add.bitmapText(400, 100, 'myFont', 'Score: 0', 32); // DynamicBitmapText (per-character manipulation via callback) const fancy = this.add.dynamicBitmapText(400, 200, 'myFont', 'Wavy!', 32); fancy.setDisplayCallback(function (data) { data.y += Math.sin(data.index * 0.5 + fancy.scene.time.now * 0.005) * 10; return data; }); ``` -------------------------------- ### Start Phaser PathFollower with shorthand duration Source: https://github.com/phaserjs/phaser/blob/master/skills/curves-and-paths/SKILL.md Use a numeric value as a shorthand for the duration property when starting a follower. ```javascript // Shorthand: pass just a duration number enemy.startFollow(5000); // Equivalent to: enemy.startFollow({ duration: 5000 }); ``` -------------------------------- ### Create Audio Instances in Phaser Source: https://github.com/phaserjs/phaser/wiki/Audio These examples show how to create single-play and looping audio instances using `game.add.audio`. The second parameter can set volume, and the third can enable looping. ```javascript var my_music = game.add.audio("my_music") var my_music_loop = game.add.audio("my_music", 1, true) ``` -------------------------------- ### get() vs values: Copies and Live References Source: https://github.com/phaserjs/phaser/blob/master/skills/data-manager/SKILL.md Demonstrates the critical difference between get() which returns a copy for primitives and values which provides a live proxy that triggers CHANGE_DATA events. For objects, get() returns the stored reference; mutations do not trigger events unless re-set. ```javascript // get() returns a copy for primitives -- modifying the local variable does NOT update the DataManager let score = this.data.get('score'); score += 10; // local copy only, DataManager still has the old value // values provides a live proxy -- assignment triggers CHANGE_DATA event this.data.values.score += 10; // updates the DataManager AND emits changedata-score // For objects, get() returns the stored reference (not a deep copy) const stats = this.data.get('stats'); stats.hp -= 10; // mutates the stored object but does NOT trigger events this.data.set('stats', { ...stats }); // re-set with new reference to trigger event ``` -------------------------------- ### Quick Start Camera Configuration in Phaser 4 Source: https://github.com/phaserjs/phaser/blob/master/skills/cameras/SKILL.md Demonstrates common camera operations in a Phaser Scene's create() method, including accessing the main camera, scrolling, centering, zooming, following a sprite, setting bounds, applying fade effects, and adding filters. ```js // In a Scene's create() method: // Access the default camera (created automatically) const cam = this.cameras.main; // Scroll the camera to look at a different part of the world cam.setScroll(200, 100); // Center camera on a world coordinate cam.centerOn(400, 300); // Zoom in (2x) -- values < 1 zoom out, > 1 zoom in cam.setZoom(2); // Follow a sprite with smooth lerp cam.startFollow(player, false, 0.1, 0.1); // Constrain the camera to the world bounds cam.setBounds(0, 0, 2048, 2048); // Fade in from black over 1 second cam.fadeIn(1000); // Add a filter to the camera (v4 feature) cam.filters.external.addBlur(1, 2); ``` -------------------------------- ### Create Tapered Line in WebGL Source: https://github.com/phaserjs/phaser/blob/master/skills/graphics-and-shapes/SKILL.md The setLineWidth method allows for tapering effects by specifying different start and end widths, though Canvas only supports the start width. ```javascript const line = this.add.line(400, 300, 0, 0, 200, 100, 0xffffff); // setLineWidth(startWidth, endWidth) — endWidth is WebGL only (tapering effect) line.setLineWidth(4, 1); // tapers from 4px to 1px (Canvas uses startWidth only) ``` -------------------------------- ### Basic Phaser Shader Configurations Source: https://github.com/phaserjs/phaser/blob/master/docs/Phaser 4 Shader Guide/Phaser 4 Shader Guide.md Illustrates simple configurations for a Phaser Shader, showing how to use either a loaded GLSL file via 'fragmentKey' or inline GLSL code via 'fragmentSource'. ```ts // When using a loaded GLSL file: const config1 = { name: 'myShader', fragmentKey: 'Marble' }; // Or when using inline GLSL code: const glsl = '// GLSL code goes here'; const config2 = { name: 'myOtherShader', fragmentSource: glsl }; ``` -------------------------------- ### Example Phaser Shader Addition for Texture Mapping Source: https://github.com/phaserjs/phaser/blob/master/docs/Phaser 4 Shader Guide/Phaser 4 Shader Guide.md Provides an example of a 'ShaderAdditionConfig' to add texture mapping capabilities to a default fragment shader by injecting uniform declarations and processing logic. ```ts const addition = { name: 'myAddition', additions: [ { key: 'fragmentHeader', value: 'uniform sampler2D iChannel0;' }, { key: 'fragmentProcess', value: 'fragColor = texture2D(iChannel0, outTexCoord);' } ] }; ``` -------------------------------- ### Method `getProgress()` Source: https://github.com/phaserjs/phaser/blob/master/skills/animations/SKILL.md Get progress 0-1 ```APIDOC ## getProgress sprite.anims.getProgress ### Description Get the current progress of the animation as a value between 0 and 1. ### Method getProgress ### Endpoint sprite.anims.getProgress ### Response #### Success Response (200) - **progress** (number) - The current progress of the animation (0-1). #### Response Example ```json { "progress": 0.75 } ``` ``` -------------------------------- ### Method `getTotalFrames()` Source: https://github.com/phaserjs/phaser/blob/master/skills/animations/SKILL.md Get total frame count ```APIDOC ## getTotalFrames sprite.anims.getTotalFrames ### Description Get the total number of frames in the current animation. ### Method getTotalFrames ### Endpoint sprite.anims.getTotalFrames ### Response #### Success Response (200) - **frameCount** (number) - The total number of frames. #### Response Example ```json { "frameCount": 12 } ``` ``` -------------------------------- ### Phaser DynamicBitmapText with Display Callback and Scrolling Source: https://github.com/phaserjs/phaser/blob/master/skills/text-and-bitmaptext/SKILL.md Demonstrates creating a DynamicBitmapText object and using a per-character display callback for custom visual effects. It also shows how to set a scrolling text window. ```js const dynamic = this.add.dynamicBitmapText(100, 100, 'pixelFont', 'Dynamic!', 32); // Per-character display callback -- invoked each render frame per character dynamic.setDisplayCallback(function (data) { // data properties: parent, tint, index, charCode, x, y, scale, rotation, data data.x += Math.sin(data.index + dynamic.scene.time.now * 0.01) * 5; data.y += Math.cos(data.index + dynamic.scene.time.now * 0.01) * 5; return data; }); // Scrolling text window dynamic.setSize(200, 50); // crop region in pixels dynamic.setScrollX(10); dynamic.setScrollY(0); ``` -------------------------------- ### Define pre-boot and post-boot callbacks in Phaser Source: https://github.com/phaserjs/phaser/blob/master/skills/game-setup-and-config/SKILL.md Use callbacks to execute logic before or after the game boots. Note that game systems are not available during preBoot. ```javascript const config = { type: Phaser.AUTO, width: 800, height: 600, callbacks: { preBoot: function (game) { // Runs before Phaser boots. Game systems not yet available. }, postBoot: function (game) { // Runs after boot. All systems ready, game loop starting. } }, scene: MyScene }; ``` -------------------------------- ### Method `getFrameName()` Source: https://github.com/phaserjs/phaser/blob/master/skills/animations/SKILL.md Get the current frame key ```APIDOC ## getFrameName sprite.anims.getFrameName ### Description Get the key of the current animation frame. ### Method getFrameName ### Endpoint sprite.anims.getFrameName ### Response #### Success Response (200) - **frameKey** (string) - The key of the current animation frame. #### Response Example ```json { "frameKey": "frame_003" } ``` ``` -------------------------------- ### Configure Full-Window Responsive Game Source: https://github.com/phaserjs/phaser/blob/master/skills/game-setup-and-config/SKILL.md Use RESIZE mode with 100% width/height to make the game fill its parent container and respond to window resizing. ```javascript const config = { type: Phaser.AUTO, scale: { mode: Phaser.Scale.RESIZE, parent: 'game-container', width: '100%', height: '100%' }, scene: MyScene }; ``` -------------------------------- ### Method `getName()` Source: https://github.com/phaserjs/phaser/blob/master/skills/animations/SKILL.md Get the current animation key ```APIDOC ## getName sprite.anims.getName ### Description Get the key of the currently playing animation. ### Method getName ### Endpoint sprite.anims.getName ### Response #### Success Response (200) - **key** (string) - The key of the current animation. #### Response Example ```json { "key": "idle" } ``` ``` -------------------------------- ### Configuring URL Resolution and Prefixes Source: https://github.com/phaserjs/phaser/blob/master/skills/loading-assets/SKILL.md Use setBaseURL, setPath, and setPrefix to manage asset locations and cache keys globally. ```javascript preload() { // Set base URL (prepended to all relative paths) this.load.setBaseURL('https://cdn.example.com/'); // Set path (prepended after baseURL, before filename) this.load.setPath('assets/images/'); // Set key prefix (prepended to the cache key, not the URL) this.load.setPrefix('LEVEL1.'); // Loads from: https://cdn.example.com/assets/images/hero.png // Cached with key: LEVEL1.hero this.load.image('hero', 'hero.png'); // Absolute URLs bypass the path/baseURL this.load.image('cloud', 'https://other-server.com/cloud.png'); } ``` -------------------------------- ### Data Events and Proxy Access Source: https://github.com/phaserjs/phaser/blob/master/skills/data-manager/SKILL.md Understanding the difference between get() and the values proxy, and how events are routed. ```APIDOC ## Data Events and Proxy ### Description Phaser uses a proxy system for live data updates and an event system for change notifications. ### get() vs values - **get(key)**: Returns a copy for primitives. Modifying the local variable does NOT update the DataManager. - **values**: A live proxy. Assignment (e.g., `this.data.values.score += 10`) triggers the `CHANGE_DATA` event. ### Event Routing - **GameObject**: Events emit on the GameObject (`sprite.on('changedata-hp', ...)`). - **Scene (this.data)**: Events emit on the Scene event bus (`this.events.on('changedata-score', ...)`). - **Registry (this.registry)**: Events emit on the Registry's own emitter (`this.registry.events.on('changedata-score', ...)`). ### Example ```js // Listen for specific key change this.data.events.on('changedata-score', (parent, value, previousValue) => { console.log('New Score:', value); }); ``` ``` -------------------------------- ### Phaser BitmapText Creation and Basic Manipulation Source: https://github.com/phaserjs/phaser/blob/master/skills/text-and-bitmaptext/SKILL.md Shows how to create static BitmapText objects, set alignment, and modify text content, font size, and spacing. A bitmap font must be preloaded for this to work. ```js // Load in preload: this.load.bitmapFont('pixelFont', 'font.png', 'font.xml'); // Static BitmapText -- fast, batched rendering const bmpText = this.add.bitmapText(100, 100, 'pixelFont', 'Hello', 32); // With alignment (for multi-line) const aligned = this.add.bitmapText(100, 200, 'pixelFont', 'Line 1\nLine 2', 24, 1); // align: 0 = left, 1 = center, 2 = right // Convenience alignment methods bmpText.setLeftAlign(); bmpText.setCenterAlign(); bmpText.setRightAlign(); // Modify text bmpText.setText('Updated!'); bmpText.text = 'Also works'; // Font size bmpText.setFontSize(48); bmpText.fontSize = 48; // Spacing bmpText.setLetterSpacing(2); bmpText.setLineSpacing(5); // Word wrap by max pixel width bmpText.setMaxWidth(200); ``` -------------------------------- ### Query Sounds in Manager Source: https://github.com/phaserjs/phaser/blob/master/skills/audio-and-sound/SKILL.md Retrieve sounds by key, check playback status, or get all sounds in the manager. ```javascript this.sound.get('coin'); // first sound with key, or null this.sound.getAll('coin'); // all sounds with key this.sound.getAll(); // every sound in the manager this.sound.getAllPlaying(); // all currently playing sounds this.sound.isPlaying('coin'); // true if any 'coin' sound is playing this.sound.isPlaying(); // true if any sound is playing ``` -------------------------------- ### Create a Basic Scene with Lifecycle Methods in JavaScript Source: https://github.com/phaserjs/phaser/blob/master/skills/scenes/SKILL.md Implement the core lifecycle methods to handle data initialization, asset loading, and frame-by-frame updates. Ensure the super() call in the constructor includes the unique scene key. ```javascript // Minimal scene with all lifecycle methods class GameScene extends Phaser.Scene { constructor() { super('GameScene'); } init(data) { // Called first. Receives data passed from other scenes. // 'data' is whatever was passed via scene.start('GameScene', { level: 1 }) this.level = data.level || 1; } preload() { // Called after init. Load assets here. this.load.image('logo', 'assets/logo.png'); } create(data) { // Called after preload completes. Set up game objects. // 'data' is the same object passed to init. this.add.image(400, 300, 'logo'); } update(time, delta) { // Called every frame while scene is RUNNING. // time: current time (ms), delta: ms since last frame (smoothed) } } const config = { width: 800, height: 600, scene: [GameScene] }; const game = new Phaser.Game(config); ``` -------------------------------- ### GET BaseCamera Properties Source: https://github.com/phaserjs/phaser/blob/master/skills/cameras/references/REFERENCE.md Core configuration properties for the BaseCamera class, defining the viewport and rendering state. ```APIDOC ## GET BaseCamera Properties ### Description Access and modify the fundamental state of a camera instance, including its position in the world and its viewport on the canvas. ### Method GET/SET ### Endpoint Phaser.Cameras.Scene2D.BaseCamera ### Parameters #### Request Body - **scrollX** (number) - World position X the camera is looking at. - **scrollY** (number) - World position Y the camera is looking at. - **zoom** (number) - Shortcut to set both zoomX and zoomY (default 1). - **rotation** (number) - Camera rotation in radians. - **x** (number) - Viewport X position on the canvas. - **y** (number) - Viewport Y position on the canvas. - **width** (number) - Viewport width in pixels. - **height** (number) - Viewport height in pixels. - **alpha** (number) - Opacity of the camera (0 to 1). - **visible** (boolean) - Whether the camera renders to the canvas. - **backgroundColor** (Color) - Background fill color for the camera. ### Request Example { "scrollX": 100, "scrollY": 100, "zoom": 2, "backgroundColor": "#000000" } ### Response #### Success Response (200) - **worldView** (Rectangle) - Read-only rectangle of the visible world area. - **midPoint** (Vector2) - Read-only center of the camera in world coordinates. ``` -------------------------------- ### Create Phaser Game App using npm Source: https://github.com/phaserjs/phaser/blob/master/README.md Use the npm create command to start a new Phaser game project with the official CLI tool. This tool offers an interactive selection of project templates. ```bash npm create @phaserjs/game@latest ``` -------------------------------- ### Stagger animation playback across multiple sprites Source: https://github.com/phaserjs/phaser/blob/master/skills/animations/SKILL.md Start animations on a group of sprites with a sequential delay between each. ```js const enemies = this.add.group({ key: 'enemy', repeat: 9 }); this.anims.staggerPlay('walk', enemies.getChildren(), 100); // Each sprite starts 100ms after the previous. Pass staggerFirst: false to skip delay on first. ``` -------------------------------- ### Addition Tag Example Source: https://github.com/phaserjs/phaser/blob/master/docs/Phaser 4 Shader Guide/Phaser 4 Shader Guide.md Optional tags used to categorize Additions or provide access if names change. ```javascript 'ITERATION' ``` -------------------------------- ### Create Phaser Game App using bun Source: https://github.com/phaserjs/phaser/blob/master/README.md Use the bun create command to start a new Phaser game project with the official CLI tool. This tool offers an interactive selection of project templates. ```bash bun create @phaserjs/game@latest ``` -------------------------------- ### Full Cutscene Example with Timeline Source: https://github.com/phaserjs/phaser/blob/master/skills/time-and-timers/SKILL.md Complete scene implementation choreographing a cutscene with callbacks, tweens, sounds, property sets, and custom events. Demonstrates typical cutscene flow and scene transition. ```javascript class CutsceneScene extends Phaser.Scene { create() { const timeline = this.add.timeline([ { at: 0, run: () => { console.log('Start!'); } }, { at: 1000, tween: { targets: this.player, x: 400, duration: 500, ease: 'Power2' } }, { at: 1500, sound: 'doorOpen' }, { at: 2000, set: { visible: true }, target: this.door }, { from: 500, run: () => { console.log('Relative timing'); } }, { at: 5000, event: 'cutsceneDone', stop: true } ]); timeline.on('cutsceneDone', () => { this.scene.start('GameScene'); }); timeline.play(); } } ``` -------------------------------- ### Timer once with setTimeout Source: https://github.com/phaserjs/phaser/wiki/Misc Triggers a function once after a delay. This example includes a cleanup pattern to clear the timer reference. ```javascript var my_timer = setTimeout(myStopFunction,3000); // target function, time in ms function myStopFunction() { alert("hello") clearTimeout(my_timer); my_timer = null } ``` -------------------------------- ### Tween Events Source: https://github.com/phaserjs/phaser/blob/master/skills/events-system/SKILL.md Describes events dispatched by individual Tween instances during their lifecycle, such as start, update, repeat, and complete. ```APIDOC ## Tween Events (Phaser.Tweens.Events) ### Description Events emitted by individual tween instances during their lifecycle. ### Emitter Individual tween instances. ### Events | Constant | String | When | |---|---|---| | `TWEEN_ACTIVE` | `'active'` | Tween becomes active | | `TWEEN_START` | `'start'` | Tween starts first play | | `TWEEN_UPDATE` | `'update'` | Tween updates a value | | `TWEEN_YOYO` | `'yoyo'` | Tween yoyos (reverses direction) | | `TWEEN_REPEAT` | `'repeat'` | Tween repeats | | `TWEEN_LOOP` | `'loop'` | Tween loops | | `TWEEN_PAUSE` | `'pause'` | Tween paused | | `TWEEN_RESUME` | `'resume'` | Tween resumed | | `TWEEN_COMPLETE` | `'complete'` | Tween finishes | | `TWEEN_STOP` | `'stop'` | Tween stopped manually | ``` -------------------------------- ### Configure Arcade Physics in headless tests Source: https://github.com/phaserjs/phaser/blob/master/tests/TESTING.md Pass a physics configuration object to helper.createGame to initialize the Arcade Physics engine. This allows testing of physics bodies and collisions. ```javascript scene = await helper.createGame({ physics: { default: 'arcade', arcade: { debug: false, gravity: { y: 0 } } } }); var sprite = scene.physics.add.sprite(0, 0, '__DEFAULT'); expect(sprite.body).toBeDefined(); ``` -------------------------------- ### Basic Tween Pattern Source: https://github.com/phaserjs/phaser/blob/master/skills/tweens/SKILL.md Simple example of tweening multiple properties on a single target with a specified easing function. ```javascript this.tweens.add({ targets: this.player, x: 500, y: 300, duration: 1000, ease: 'Sine.easeInOut' }); ``` -------------------------------- ### Create Phaser Game App using npx Source: https://github.com/phaserjs/phaser/blob/master/README.md Use the npx command to start a new Phaser game project with the official CLI tool. This tool offers an interactive selection of project templates. ```bash npx @phaserjs/create-game@latest ``` -------------------------------- ### Range Compression Notation Source: https://github.com/phaserjs/phaser/blob/master/docs/Phaser Compact Texture Atlas Format Specification/Phaser Compact Texture Atlas Format Specification.md Syntax for expanding sequential asset names with support for zero-padding based on the start string length. ```text frame#1-23 → frame1, frame2, frame3, ..., frame23 walk_#01-08 → walk_01, walk_02, ..., walk_08 idle#000-059 → idle000, idle001, ..., idle059 ``` -------------------------------- ### Updating Uniforms with setupUniforms in Phaser Shader Source: https://github.com/phaserjs/phaser/blob/master/docs/Phaser 4 Shader Guide/Phaser 4 Shader Guide.md Shows how to use the 'setupUniforms' function to dynamically update shader uniforms, such as animating values or changing textures, on every render. ```ts // How to update the `time` uniform on a Shader: const config = { setupUniforms: (setUniform, drawingContext) => { setUniform('time', this.game.loop.getDuration()); } }; ``` -------------------------------- ### Draw Line Vector Shape Source: https://github.com/phaserjs/phaser/wiki/Graphics Draw a line by specifying start and end points using moveTo and lineTo methods. ```javascript shape.moveTo(30, 30); // x, y shape.lineTo(600, 300); // x, y ``` -------------------------------- ### Loading Methods - General Usage Source: https://github.com/phaserjs/phaser/blob/master/skills/loading-assets/references/REFERENCE.md General information about Phaser loading methods. All methods support flexible parameter passing and batch loading of multiple files. ```APIDOC ## General Loading Method Usage ### Method Invocation All loading methods are called on `this.load` within a Scene. **Example:** ```javascript scene.load.image('key', 'path/to/image.png'); ``` ### Parameter Formats All methods accept parameters in multiple formats: #### 1. Positional Arguments ```javascript this.load.image('myImage', 'assets/image.png'); this.load.spritesheet('player', 'assets/player.png', { frameWidth: 32, frameHeight: 48 }); ``` #### 2. Single Config Object ```javascript this.load.image({ key: 'myImage', url: 'assets/image.png' }); ``` #### 3. Array of Config Objects (Batch Loading) ```javascript this.load.image([ { key: 'image1', url: 'assets/image1.png' }, { key: 'image2', url: 'assets/image2.png' }, { key: 'image3', url: 'assets/image3.png' } ]); ``` ### Asset Storage Assets are stored in global game-level caches (not per-Scene): - **Textures:** Stored in the Texture Manager - **Other Data:** Stored in typed sub-caches (audio cache, JSON cache, etc.) This means loaded assets are accessible from any Scene in the game. ``` -------------------------------- ### Easing Functions Source: https://github.com/phaserjs/phaser/blob/master/skills/tweens/SKILL.md A list of available easing functions in PhaserJS, including power aliases, full types, and usage examples. ```APIDOC ## Easing Functions ### Description All easing names are case-insensitive. Use the string name in the `ease` config property. ### Power Aliases | Name | Equivalent | |---|---| | `Power0` | `Linear` | | `Power1` | `Quad.easeOut` (Quadratic Out) | | `Power2` | `Cubic.easeOut` | | `Power3` | `Quart.easeOut` (Quartic Out) | | `Power4` | `Quint.easeOut` (Quintic Out) | ### Full Easing List Each type supports `.easeIn`, `.easeOut`, `.easeInOut` variants. The bare name defaults to Out. **Types:** `Quad`, `Cubic`, `Quart`, `Quint`, `Sine`, `Expo`, `Circ`, `Elastic`, `Back`, `Bounce`. **Special:** `Linear` (no easing), `Stepped` (discrete steps -- `easeParams: [numSteps]`). **Custom:** `ease: function (t) { return t * t; }` where `t` is 0 to 1. ### Usage Examples: `'Sine.easeInOut'`, `'Bounce.easeIn'`, `'Cubic.easeOut'`, `'Back'` (same as `'Back.easeOut'`). ```