Utilizing Objects as Properties in Phaser.Scene in Phaser 3

I've just started working with Phaser using TypeScript and I'm facing an issue. I attempted to move my main objects out of the create and preload methods by loading them as Phaser.Scene class properties. However, after making this change, my game only displays a black screen with no errors...

Can someone please review the code below and help me identify what may be causing this problem?

import * as Phaser from 'phaser';

const sceneConfig = {
    active: false,
    visible: false,
    key: 'Game',
}

export default class GameScene extends Phaser.Scene {
    platforms : Phaser.Physics.Arcade.StaticGroup
    player: Phaser.Types.Physics.Arcade.SpriteWithDynamicBody 
  
    constructor() {
      super(sceneConfig);
      this.platforms = this.physics.add.staticGroup()
      this.player = this.physics.add.sprite(100, 450, 'dude')
    }
  
    preload() {
      this.load.image('sky', 'src/assets/sky.png');
      this.load.image('ground', 'src/assets/platform.png');
      this.load.image('star', 'src/assets/star.png');
      this.load.image('bomb', 'src/assets/bomb.png');
      this.load.spritesheet('dude', 
          'src/assets/dude.png',
          { frameWidth: 32, frameHeight: 48 }
      );
    }
   
    create() {
      
      this.add.image(0, 0, 'sky').setOrigin(0,0) 
  
  
      this.platforms.create(400, 568, 'ground').setScale(2).refreshBody();
  
      this.platforms.create(600, 400, 'ground');
      this.platforms.create(50, 250, 'ground');
      this.platforms.create(750, 220, 'ground');
      
      this.player.body.setGravityY(300)
      this.player.setBounce(0.2);
      this.player.setCollideWorldBounds(true);
  
      this.anims.create({
          key: 'left',
          frames: this.anims.generateFrameNumbers('dude', { start: 0, end: 3 }),
          frameRate: 10,
          repeat: -1
      });
  
      this.anims.create({
          key: 'turn',
          frames: [ { key: 'dude', frame: 4 } ],
          frameRate: 20
      });
  
      this.anims.create({
          key: 'right',
          frames: this.anims.generateFrameNumbers('dude', { start: 5, end: 8 }),
          frameRate: 10,
          repeat: -1
      });
  
      this.physics.add.collider(this.player, this.platforms);
    }
   
    public update() {
      // TODO
      var cursors = this.input.keyboard.createCursorKeys();
      if (cursors.left.isDown)
      {
          this.player.setVelocityX(-160);
  
          this.player.anims.play('left', true);
      }
      else if (cursors.right.isDown)
      {
          this.player.setVelocityX(160);
  
          this.player.anims.play('right', true);
      }
      else
      {
          this.player.setVelocityX(0);
  
          this.player.anims.play('turn');
      }
  
      if (cursors.up.isDown && this.player.body.touching.down)
      {
          this.player.setVelocityY(-330);
      }
  
    }
}

Answer №1

A common mistake is trying to add elements to the scene in the constructor when it hasn't been initialized yet.

To fix this issue, make use of a definite assignment assertion by moving these elements to the create method:

export default class GameScene extends Phaser.Scene {
  platforms!: Phaser.Physics.Arcade.StaticGroup
  player!: Phaser.Types.Physics.Arcade.SpriteWithDynamicBody 
  
  constructor() {
    super(sceneConfig);
  }
  
  create() {
    this.platforms = this.physics.add.staticGroup()
    this.player = this.physics.add.sprite(100, 450, 'dude')
    ...

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

To handle a 400 error in the server side of a NextJS application, we can detect when it

I'm facing a situation where I have set up a server-side route /auth/refresh to handle token refreshing. The process involves sending a Post request from the NextJS client side with the current token, which is then searched for on the server. If the t ...

Display Numerous Values Using Ajax

Having difficulty showing data from the 'deskripsisrt' table in a modal bootstrap? I have successfully displayed from the 'srtptr' table, but not sure how to proceed with the 'deskripsisrt' table. Here's a snippet from my ...

choosing a section within a table cell

This seems like a simple task, but I'm encountering some difficulties $("#info-table tbody tr").each(function(){ $(this).find(".label").addClass("black"); }); .black{ font-weight:bold; } <script src="https://ajax.googleapis.com/ajax/libs/j ...

Restricting the input range with JQuery

Need assistance with limiting user input in a text box for amounts exceeding a specified limit. Attempted using Ajax without success, considering jQuery as an alternative solution. Any expertise on this matter? function maxIssue(max, input, iid) { v ...

Another inquiry regarding a city autocomplete field in a global setting

While I understand that this question may have been previously asked, I have spent several days searching without finding a satisfactory answer. Some websites, such as eventful.com, etc., have an autosuggest city field with cities from all over the world ...

Creating a React component that initializes its state with an empty array

Currently, my component is designed to fetch data from an API and store a random selection of objects (currently set at 10) in an array called correctAnswerArray. To avoid selecting the same object more than once, I use the splice() method. After pushing t ...

The sequence of HTML attributes

Could there be a subjective angle to this question (or maybe not)... I work on crafting web designs and applications using Visual Studio and typically Bootstrap. When I drag and drop a CSS file into an HTML document, the code generated by Visual Studio loo ...

Modifying the default label for each bubble on a bubble chart with chartjs-plugin-datalabels

Is there a way to add labels to each bubble in the bubble chart using chartjs-plugin-datalabels? For every bubble, I'd like to display the label property of each object within the data.dataset array, such as "Grapefruit" or "Lime". Currently, I'm ...

How can I utilize the Facebook API on Tizen to share a video?

Could someone please provide guidance on how to incorporate video uploading functionality into a Tizen application using the Facebook API and HTML5? ...

How can the selected value be shown in the dropdown menu after moving to a different webpage in HTML?

My application features 4 roles displayed in a dropdown menu. When a specific role is clicked, it should go to the corresponding href link that was specified. However, I encountered an issue where after navigating to the second HTML page, the selected rol ...

In Angular, what is the best way to update the quantity of an item in a Firestore database?

Whenever I attempt to modify the quantity of an item in the cart, the quantity does not update in the firestore database. Instead, the console shows an error message: TypeError: Cannot read properties of undefined (reading 'indexOf'). It seems li ...

"Implementing a filter with multiple select options in AngularJS

As a beginner delving into Angular, I find myself working with a multiple select feature to filter a list by name. <select multiple ng-options="data.name for data in datas" ng-model="filterData"> </select> Currently, I am able to filter with ...

Utilizing HTML5 Drag and Drop feature to track the initial position of the element being dragged

Currently, I am utilizing the HTML 5 Drag and Drop API to create a sortable list with auto scroll functionality. One crucial aspect I am trying to incorporate is the ability to detect which specific part of an element was grabbed by the user. Take a look ...

Transform a <td> into a table-row (<tr>) nested within a parent <tr> inside an umbrella structure

Similar questions have been asked in the past, but I still haven't found a solution to my specific inquiry. Here it is: I have a table that needs to be sortable using a JavaScript plugin like ListJS. The key requirement is that I must have only one & ...

What methods can I use to minimize the duration of invoking the location.reload() function?

When I'm using window.location.reload() in my onClick() function, it's taking too long to reload. I tried modifying the reload call to window.location.reload(true) to prevent caching, but it's still slow. The issue seems to be with location. ...

submit the contact form information to both the database and email for further processing and storage

Currently, I have the code for connecting to a database and mail.php. I am able to save contact form data in the database successfully, but I also want to send an email to my address which I'm unsure how to do with manage_comments.php. Here are the ...

Manipulating lines and positions with jQuery

I am looking to implement a feature that allows users to choose a specific region on an image using jQuery. The functionality should be similar to the tagging feature on Facebook, but with the added bonus of being able to rotate and scale the selected area ...

After stopping the interval with clearInterval(), you can then use the res.send method

I need to continuously log the current date and time to the server console then stop logging after a specified time, returning the final date and time to the user. How do I properly utilize ClearInterval() in this scenario? const express = require(" ...

Tips for resolving issues with dynamically displaying state information based on a selected country

I'm currently working on a project that requires me to dynamically fetch the states of a specific country when a user selects the country of birth for their family members. To do this, I am utilizing AJAX. Due to limitations, I can only include detai ...

What happens when 'grid' property is undefined in modal?

I encountered an issue with my modal where I wanted to display pre-selected rows, but kept getting a 'cannot read 'grid' of undefined' error. The UI Grids are defined within the modal, and I have declared two Grid APIs with different na ...