Navigating Through Different Scenes in Phaser3

I need to switch between two scenes in my Phaser3 (version 3.21.0) app without any side effects. The first scene handles the menu with high score, while the second scene is for the actual gameplay.

Code snippets:

The app.ts file is as follows:

const config = {
    title: '<game-name>',
    width: 800,
    height: 600,
    parent: 'game',
    scene: [MenuScene, GameScene],
};

export class GameName extends Phaser.Game {
    constructor(config: any) {
        super(config);
    }
}

window.onload = () => new GameName(config);

The MenuScene.ts - relevant part shown below:

class MenuScene extends Phaser.Scene {
    constructor() { super({key: 'MenuScene'}); }

    create():void {
       console.log('create menuscreen');
       const enter = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.ENTER);
       enter.on('down', () => { this.scene.start('GameScene'); }
    }
}

The GameScene.ts - relevant code excerpt provided:

class GameScene extends Phaser.Scene {
    constructor() { super({key: 'GameScene'}); }

    create = ():void => {
       console.log('create gamescreen');
       const esc = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.ESC);
       esc.on('down', () => { this.scene.start('MenuScene'); }
    }
}

Issue and question:

When I repeatedly press Enter and Esc to switch between scenes using the provided solution, it doesn't seem to clean up the background scenes. After switching a few times, the console displays errors like in the image below after 6 switches: https://i.sstatic.net/5cp3P.png

I have tried calling this.scene.stop() before

this.scene.start('<scene-key>')
, but the issue persists. I also checked similar questions on Phaser3 Scenes transitions but couldn't find a solution. It was mentioned that the start() method should clean up or shut down the unused scenes.

How can I properly switch between scenes or clean up the currently unused scene?

Thank you!

Answer №1

This is my approach to handling game scenes

1.- Prioritizing scene over game for pause

In this setup, the scene_pause takes precedence over the game_scene as the top scene.

isPaused = this.scene.isPaused('scene_game');
if (false === isPaused) {
    this.scene.pause('scene_game');
}
const isNull = this.scene.get('scene_pause');
if (null === isNull) {
    this.scene.add('pause_scene', PauseScene, true);
}

When resuming the game

isActive = this.scene.isActive('scene_pause');
if (true === isActive) {
    this.scene.remove('scene_pause');
}
isPaused = this.scene.isPaused('scene_game');
if (true === isPaused) {
    this.scene.resume('scene_game');
}

2.- Transitioning from scene to game over state

this.scene.stop('scene_game'); // stop running Update first
... // save game state and score
this.scene.remove('scene_game'); // Remove scene for re-addition when starting the game again
this.scene.stop('scene_ui');
this.scene.switch('scene_game_over');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting problem with @Input number in Angular 2

Here is the component in question: <component value="3"></component> This is the code for the component: private _value:number; get value(): number { return this._value; } @Input() set value(value: number) { console.log(v ...

How can I retrieve the specific element of *ngFor loop within the component.ts

Currently, I am utilizing the angular2-swing library and have integrated the following code into my template: <ul class="stack" swing-stack [stackConfig]="stackConfig" #myswing1 (throwout)="onThrowOut($event)"> <li swing-card #restaurantC ...

The search functionality in Angular 2 using Typescript is not working properly, as the button is not triggering the

I've been working on developing a search feature that utilizes text input to look up information about corporations through a government API (https://github.com/usagov/Corporate-Consumer-Contact-API-Documentation). Within my project, I have an HTML p ...

Exclude certain files when conducting SonarQube Code Coverage Analysis for Angular 7

How can I improve code coverage in SonarQube Analysis by excluding ts.files? I attempted the following code: "test": { "builder": "@angular-devkit/build-angular:karma", "options": { "main": "src/test.ts", "poly ...

Encountered the error message 'The function getStaticPaths is not defined' while working with Next.js

As a newcomer to Nextjs, I am currently working on a blog project utilizing the T3 Stack (Nextjs, Typescript, Prisma, tRPC). I have encountered an error while attempting to fetch post content by ID. Below are the relevant sections of my code. Any assistanc ...

Utilize an ion-searchbar along with a FormGroup to ensure that searches are only performed when the entered value meets the minimum

I am attempting to create a search feature that will only begin searching when the inputted value is 3 or higher However, the method I have tried so far has not been successful :( Home.page.html <form [formGroup]="search"> <ion-se ...

Define a new type in Typescript that is equal to another type, but with the added flexibility of having optional

I have 2 categories: category Main = { x: boolean; y: number; z: string } category MainOptions = { x?: boolean; y?: number; z?: string; } In this scenario, MainOptions is designed to include some, none, or all of the attributes that belong to ...

AngularFire 2 dispatching email for password reset

I am looking to add a feature for resetting passwords or handling forgotten passwords using AngularFire2. It looks like the function sendPasswordResetEmail is either not available in AngularFire2 or the typings have not been updated yet. I tried accessing ...

A new interface property type that is customized based on the type property that is passed in

My dilemma lies in a generic interface with a field depending on the passed type. I'm exploring the possibility of having another field that can accept any type from the passed type. For instance: interface sampleObject { name: fullName age: n ...

Angular 2 Table Serial Number

I have data coming in from an API and I want to display it in a table. In the table, there is a column for serial numbers (#). Currently, I am able to show the serial numbers starting from 1 on every page. However, when I switch pages, the counting starts ...

What causes TypeScript to malfunction when using spread in components?

What is the reason for typescript breaking when props are sent to a component using a spread statement? Here's an example code snippet: type SomeComponentProps = Readonly<{ someTitle: string }> const SomeComponent = ({ someTitle }: SomeCompo ...

Can a type be formed with a generic type as the rest parameter?

After exploring the question about implementing a choice of index type on an interface Defining a choice of index type on an interface Now, I am tasked with creating a sequence of elements. Typically it would look like element1 & element2, but because ...

Guidelines for simulating ActivatedRouteSnapshot in observable testing situations

I am currently testing an observable feature from a service in Angular. This particular observable will output a boolean value based on the queryParam provided. For effective testing of this observable, it is essential to mock the queryParam value. Howev ...

Is there a way to retrieve the name of a document stored within a collection using Firebase Firestore and Firebase Storage

When fetching data from the 'users' collection in Firebase Firestore and mapping the response, I have a function that converts the array of domains and filters out any domains that do not meet certain criteria. Here's an example: Sample dom ...

What is the best practice for inserting typescript definitions and writing them when the object already has a pre-existing definition?

Apologies for this question, as I am struggling to find the necessary information due to my limited understanding of Typescript. I have integrated a jquery plugin called typeahead and added a global variable named bound on the window object for communicati ...

Tips for sending information back to the previous screen in React Native Navigation version 5

Recently, I upgraded to react native navigation version 5 and now I am facing an issue with sending data back to the previous screen when making a goBack() call. To navigate to the next view, I use: const onSelectCountry = item => { console.log(it ...

What is the best method for incorporating an Angular Component within a CSS grid layout?

I recently started learning Angular and am currently working on a project that requires the use of a CSS grid layout. However, I'm facing an issue with inserting a component inside a grid area specified by grid-area. My attempt to achieve this in app ...

Troubleshooting Problem with ES6 String Literals/Typescript in Chrome Developer Tools

I'm currently immersed in a project that involves Typescript and some of the ES6 features it offers, such as ES6 String Literals like `Something ${variable} Something else`. During my debugging process, I decided to set a breakpoint in my typescript ...

Create a well-designed function that assigns events to handlers in a generic way

Here we are continuing from the previous exploration that aims to develop a reusable mechanism for assigning incoming events (messages) to appropriate event handlers while maintaining complete type reliance. Our goal is to create a reusable function for ha ...

Dynamic Angular TreeView showcasing nested children branches

I am in need of creating a treeView that can handle dynamic data. Currently, I am utilizing the syncfusion component which can be found at this link. The challenge I am facing is that the data object I receive is incomplete, with the "children" being gene ...