Issue with music in Phaser3 game not playing correctly when transitioning to a new scene

I'm completely new to Phaser and I've encountered an issue with adding a start menu to my main platformer scene. The gameplay scene plays music seamlessly, but when I introduce a start menu, things start to go wrong. Here's a snippet of the menu code:


public create(): void {
    super.create();

    this.newGameText = this.add
        .text(+this.game.config.width / 2, +this.game.config.height / 2 - 72, "New game", { fontSize: "72px", color: "#fff" })
        .setOrigin(0.5, 0.5)
        .setInteractive();

    this.exitGameText = this.add
        .text(+this.game.config.width / 2, +this.game.config.height / 2 + 72, "Exit game", { fontSize: "72px", color: "#fff" })
        .setOrigin(0.5, 0.5)
        .setInteractive();

    this.music = this.sound.add(Keys.Musics.MainMenu, { loop: true });

    this.music.play();
}

public update(time: number, delta: number): void {
    super.update(time, delta);

    this.newGameText.on(Keys.MouseEvents.PointerDown, () => this.startGame());
    this.exitGameText.on(Keys.MouseEvents.PointerDown, () => this.exitGame());
}

private startGame(): void {
    this.scene.start(Keys.Scenes.Game);
}

private exitGame(): void {
    this.game.destroy(true, true);
}

The issue arises when the game scene starts playing its own music within the create function, like this:


this.sound.play(Keys.Musics.Level1, {
    loop: true,
    volume: 0.3,
});

Upon clicking "New game," the new scene loads but the sound quality is distorted. Adding this.music.destroy() in the startGame() function of the main menu scene resolves the sound issue, but leads to the error:

phaser.js:107083 Uncaught TypeError: Cannot read properties of null (reading 'disconnect')
at WebAudioSound.destroy (phaser.js:107083:1)

The error occurs in the following section of the source code:

https://i.sstatic.net/OBK3Z.png

I'm wondering what I might be doing wrong in this scenario. Any insights or suggestions would be greatly appreciated.

You can access the source code here.

Additionally, removing the music from the main menu did not resolve the issue.

Answer №1

To improve efficiency, consider moving the event listener hooks into the create function. It is recommended that setup tasks are handled within the create function (or sometimes in the init function). Simply add the following lines to the create function:

public create(): void {
    ...
    this.newGameText.on(Keys.MouseEvents.PointerDown, () => this.startGame());
    this.exitGameText.on(Keys.MouseEvents.PointerDown, () => this.exitGame());
}

The create function is only called once, which should suffice for these tasks.

For more information, refer to this unofficial flow chart of the Phaser game lifecycle
By the way: the update function is called 60 times per second.

Answer №2

After investigating, I uncovered the reason behind the issue.

this.newGameText.on(Keys.MouseEvents.PointerDown, () => this.startGame());

It appears that this particular function is being called approximately 100 times, causing 100 scenes to start simultaneously...

Fortunately, I was able to resolve the problem by implementing the following solution:

private startGame(): void {
    if (!this.startingScene) {
        this.startingScene = true;
        this.music.stop();
        this.scene.start(Keys.Scenes.Game);
    }
}

I wonder if there is a more efficient approach to address this issue?

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

What is preventing Typescript from utilizing the includes function for arrays?

I understand that Typescript is based on ES6 or ES2015. However, I'm confused because anArray.includes('ifExist'); is only available in ES6. Even though I'm using Typescript, why am I unable to use it? The error message says that anAr ...

The attribute 'name' cannot be found within the class 'MyComponent'

I'm a beginner in Angular2 and I have no previous knowledge of version 1. Can you help me understand why this error is occurring and guide me on how to fix it? import { Component } from 'angular2/core'; @Component ({ selector: 'my- ...

What is the reason behind RematchDispatch returning a `never` type when a reducer and an effect share the same name?

Recently, I made the switch from TypeScript 4.1.2 to 4.3.2 with Rematch integration. Here are the Rematch packages in use: "@rematch/core": "2.0.1" "@rematch/select": "3.0.1" After the upgrade, a TypeScript error p ...

styled components are having issues with background gradients and opacity not functioning properly

Hello, I am currently working with styled components and have the following global style code: const GlobalStyle = createGlobalStyle` html{ font-family: roboto; background: linear-gradient(45deg,rgba(137,255,255,0.5),rgba(161,252,143, 0 ...

The arrow function in Jest is missing a name property

Currently, my setup includes: node.js: 9.8.0 Jest: 23.4.2 ts-jest: 23.1.3 typescript: 2.9.2 While attempting the following in my *.test.ts files: const foo = () => 'bar'; console.log(foo.name); // '' foo contains the name pro ...

NgFor is designed to bind only to Iterables like Arrays

After exploring other questions related to the same error, I realized that my approach for retrieving data is unique. I am trying to fetch data from an API and display it on the page using Angular. The http request will return an array of projects. Below ...

Issue with ToggleButtonGroup causing React MUI Collapse to malfunction

I'm having trouble implementing a MUI ToggleButtonGroup with Collapse in React. Initially, it displays correctly, but when I try to hide it by selecting the hide option, nothing happens. Does anyone have any suggestions on what might be causing this ...

Vercel encountered issues with "validating code quality and type correctness" during deployment but was successful when performed locally

Running "next build" locally and "vercel build" both work smoothly. However, once deployed to vercel, the "Linting and checking validity of types" fails during the build process. It seems like TypeScript is stricter when building on vercel even with the sa ...

Display the length of the product array when I have multiple JSON objects

I am working with the following JSON data: { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "_id": "12123", "dateCreated": "2019-12-03T13:45:30.418Z", "pharmacy_id": "011E7523455533 ...

Discovering items located within other items

I am currently attempting to search through an object array in order to find any objects that contain the specific object I am seeking. Once found, I want to assign it to a variable. The interface being used is for an array of countries, each containing i ...

The output type of a function given an input

Essentially, I have successfully rendered a return type for my combined reducers using the following code: const rootReducer = combineReducers({ notes: notesReducer, categories: categoriesReducer, flyout: flyoutReducer // more reducers }); export ...

Improving the management of user input in Lit components

I am seeking a more efficient method to manage all inputs within my lit component while minimizing the code usage. I am also employing Typescript in this process, utilizing @change=${this.handleInput} for all input fields. Below is an example of how the ha ...

Compile time error due to TypeScript enumeration equality issue

Currently, I am developing a system to manage user roles within my website using TypeScript enumeration. This will allow me to restrict access to certain parts of the site based on the user's role. The primary challenge I am facing is comparing the u ...

Removing items from an array within an object stored in local storage using an Ionic application

One of my challenges involves an Ionic App that stores data in the localStorage. I need to remove specific items from an array within an object in the localStorage when a user clicks on them. Even though I have the code below, it doesn't seem to be f ...

Angular 8 bug: Requiring 2-3 arguments, received only 1

Currently deepening my knowledge in Angular and I encountered a situation within one of my services agree(id: string) { const headers = new HttpHeaders('Content-Type: application/json'); return this.HttpClient.put(`${this.apiUrl}/agree/` ...

Managing middleware in tRPC: Utilizing multiple methods for a single route call?

We're currently working on a group project with a tight deadline of just a few weeks. Our team has opted to utilize the T-3 stack for this project and have chosen tRPC as the server framework. While I am familiar with express, I am finding it challeng ...

React Native: Javascript library with typings not recognized as a module

I am currently facing a challenge of integrating the Microsoft Playfab Javascript Library into my React Native app following the recommendations provided here. The library comes with typings and is structured as illustrated here. In my file playfabWrapper. ...

DOCKER: Encounter with MongooseError [MongooseServerSelectionError] - Unable to resolve address for mongo

I am currently attempting to establish a connection between MongoDB and my application within a Docker container. Utilizing the mongoose package, here is the code snippet that I have implemented: mongoose.connect("mongodb://mongo:27016/IssueTracker", { us ...

Error TS2307 - Module 'lodash' not found during build process

Latest Update I must apologize for the confusion in my previous explanation of the issue. The errors I encountered were not during the compilation of the Angular application via Gulp, but rather in the Visual Studio 'Errors List'. Fortunately, I ...

What is the best approach to integrating payment solutions into a React Native application running on version 0

Seeking advice on integrating payment systems in React Native 0.70. Previously utilized react-native-credit-card-input and react-native-credit-card-input-plus with earlier versions, but they are now incompatible. ...