How can you destroy an object on click in Phaser 3? What if you have many objects on the stage? With this code, the object clicked gets passed to the function and destroyed
class SceneMain extends Phaser.Scene {
constructor() {
super('SceneMain');
}
preload() {
this.load.image("robot", "images/robot.png");
}
create() {
//add the sprite
this.robot = this.add.sprite(250, 250, "robot");
//set the origin to the center of the robot
this.robot.setOrigin(0.5, 0.5);
//set the robot to be clickable
this.robot.setInteractive();
//add a listener to the scene
//this will pass the object clicked to the function
this.input.on('gameobjectdown', this.onClicked.bind(this));
}
//pointer is the mouse or finger touch that triggered the event
onClicked(pointer, objectClicked) {
objectClicked.destroy();
}
update() {}
}