Can't figure out how I can change the scene

Working on a simple code, I have troubles to get working the change of a scene by clicking on a simple image. Let me show you the sample code:

// Scene for testing purpose
class Home extends Phaser.Scene {
  constructor(){
    super('home');
  }
  
  create(){
    let t = this;
    t.addIconApps();
  }

  // --- Home Screen Apps
  addIconApps(){
    let t = this;
    t.clockIconApp = new IconApp(this, 32, 32, 'clock');
  }
}

class IconApp extends Phaser.GameObjects.Image {
  constructor(scene, x, y, sprite) {
    super(scene, x, y, sprite);
    this.setInteractive();
    this.setOrigin(0);
    this.setAlpha(0.5);
    this.init();
    this.scene.add.existing(this);
  }

  init(){
    let t = this;
    // --- Open App
    t.on('pointerdown', t.clicked);
  }

  clicked(scene){
    let t = this;
    t.scene.start('AnotherScene');
  }
}

Debugging this, the console raises this error: “t.scene.start is not a function”.

What am I doing wrong?

You try to start the new scene from within your Phaser.GameObjects.Image class. So when you say this.scene.start, this refers to the Image instance.

The start method only exists on the SceneManager class, but the scene property on the image refers to the actual Scene class that the image was added to.

Does that make sense?

1 Like

Yep, it makes sense. So I need to put the interactive method ‘on’ outside the extended class Image, isn’t?

t.clockIconApp = new IconApp(this, 32, 32, 'clock');
t.clockIconApp.on('pointerdown', function(e) { t.scene.start('boot'); });

btw, is there a way to encapsulate this interaction inside the extended class?

Sure is!

The start method lives on the scene property of your Scene. That’s why this.scene.start works when this refers to your scene.

When you’re in your extended Image class, the this.scene property is your Scene. So since you’ve got a reference to your scene from within your image class, you can take it one step further and access all of the Scene’s properties from that reference: this.scene.scene.start

It works! Thank you for your time and knowledge.

1 Like