Understanding Phaser capability of running multiple Scenes simoultaneously with a real world example: continous particle scrolling background while main Scene restarts

Imagine you are building a game with an animated backgound, and you have to restart the scene hosting the game.

How to restart the game without stopping – and restarting – the animated background too?

By placing the background in another scene, then calling both the background scene and the main game scene from a container scene.

Look at this example:

The game scene is the one with the text, while scrolling background has been placed in another scene.

When you click on the canvas, game scene restarts but the scrolling background does not.

This is possible thanks to Phaser which allows to have multiple scenes running simultaneously.

This prototype has four scenes: PreloadAssets, PlayGame, GameScene and ParticleScene.

PreloadAssets preloads all assets, then calls PlayGame.

PlayGame is the main scene, with launches two scenes: GameScene and ParticleScene. These scenes aren’t called with scene.start("PlayGame") as usual, but with scene.launch("ParticleScene").

The key to this approach using launch rather than start.

Look at the source code:

let game;
window.onload = function() {
    let gameConfig = {
        type: Phaser.AUTO,
        scale: {
            mode: Phaser.Scale.FIT,
            autoCenter: Phaser.Scale.CENTER_BOTH,
            parent: "thegame",
            width: 640,
            height: 320
        },
        scene: [PreloadAssets, PlayGame, GameScene, ParticleScene]
    }
    game = new Phaser.Game(gameConfig);
    window.focus()
}

class PreloadAssets extends Phaser.Scene {
    constructor() {
        super("PreloadAssets");
    }
    preload() {
        this.load.image("square", "square.png");
    }
    create() {
        this.scene.start("PlayGame");
    }
}

class PlayGame extends Phaser.Scene {
    constructor(){
        super("PlayGame");
    }
    create(){
        this.scene.launch("ParticleScene");
        this.scene.launch("GameScene");
    }
}

class ParticleScene extends Phaser.Scene {
    constructor() {
        super("ParticleScene");
    }
    create() {
        let line = new Phaser.Geom.Line(-100, -100, game.config.width + 100, -100);
        let particles = this.add.particles("square");
        let emitter = particles.createEmitter({
            x: 0,
            y: 0,
            scale: {
                min: 0.05,
                max: 0.1
            },
            alpha: {
                min: 0.2,
                max: 0.4
            },
            angle: 90,
            speed: 50,
            frequency : 100,
            lifespan: 10000,
            emitZone: {
                source: line
            }
        });
    }
}

class GameScene extends Phaser.Scene {
    constructor() {
        super("GameScene");
    }
    create() {
        let d = new Date();
        var dateString = d.getUTCFullYear() + "/" + ("0" + (d.getUTCMonth()+1)).slice(-2) + "/" + ("0" + d.getUTCDate()).slice(-2) + " " + ("0" + d.getUTCHours()).slice(-2) + ":" + ("0" + d.getUTCMinutes()).slice(-2) + ":" + ("0" + d.getUTCSeconds()).slice(-2);
        let text = this.add.text(game.config.width / 2, game.config.height / 2, "Scene created on " + dateString + "\nClick to reload this scene\nwhile keeping background particles", { fontFamily: 'Arial', fontSize: 24  });
        text.setOrigin(0.5)
        let tintColor = Phaser.Utils.Array.GetRandom([0x62bd18, 0xff5300, 0xd21034, 0xff475c, 0x8f16b2, 0x588c7e, 0x8c4646, 0x1abc9c, 0x34495e, 0xe67e22, 0x7f8c8d]);
        this.cameras.main.setBackgroundColor(tintColor);
        this.input.on("pointerdown", function() {
            this.scene.start("GameScene");
        }, this);
    }
}

Using this Phaser feature allows us to restart scenes while keeping other scene, to create complex backgrounds or GUIs. Download the source code.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

215 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stairs
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers