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