Add Phaser 2 style buttons in Phaser 3

Phaser 2 had a very convenient way of adding buttons to a state. Phaser 3 has got rid of those buttons but if we want to keep the habit of adding buttons in Phaser 3 scenes like we used to in Phaser 2, following lines will help achieve it.

Phaser.Scene.prototype.addButton = function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame) {
    // add a button
    let btn = this.add.sprite(x, y, key, outFrame).setInteractive();
    btn.on('pointerover', function (ptr, x, y) { this.setFrame(overFrame); });
    btn.on('pointerout', function (ptr) { this.setFrame(outFrame); });
    btn.on('pointerdown', function (ptr) { this.setFrame(downFrame); });
    btn.on('pointerup', callback.bind(callbackContext, btn));

    return btn;
};

Above piece of code can now be used

var button = this.addButton(100, 100, 'buttons', this.clickButton, this, overFrame, outFrame, downFrame);

clickButton event can be defined as following

clickButton(button) {
   // use this to access scene
   // button is also available as the first param
}

 


Leave A Comment

Your email address will not be published. Required fields are marked *