Jump to content

Toggle Button


Sturb
 Share

Recommended Posts

So I made a toggle button that extends Phaser.Button. Figure I would share it seeing as I couldn't find any other implementation of something similar (if I missed something, then I'm sorry). I wrote this in Typescript and am posting that code. The Javascript is ugly because it's auto generated. It shouldn't be too hard to convert. Possibly something that could go in the engine itself.

 

/** * Class ToggleButton */export class ToggleButton extends Phaser.Button {    /* Member Variables */    toggle: Phaser.Image;    toggled: boolean;    toggleSignal: Phaser.Signal;    constructor(game: Phaser.Game, toggled?: boolean, xx?: number, yy?: number, toggleX?: number, toggleY?: number, key?: string, callback?: Function, callbackContext?: any, toggleKey?: string|number, overFrame?: string|number, outFrame?: string|number, downFrame?: string|number, upFrame?: string|number) {        super(game, xx, yy, key, this.onClick.bind(this), callbackContext, overFrame, outFrame, downFrame, upFrame);        // Set up the toggle signal.        this.toggleSignal = new Phaser.Signal();        // Set the callbacks for each toggle state.        callback ? this.toggleSignal.add(callback, callbackContext) : { };        // Set the initial toggle state.        this.toggled = toggled || false;        // Create and add the toggle image.        this.toggle = game.make.image(toggleX, toggleY, key, toggleKey);        this.addChild(this.toggle);        // Set the initial state of the toggle image.        this.toggle.visible = this.toggled;    }    /**     * ToggleButton::onClick. Callback for when the toggle button is clicked.     */    onClick() {        // Set the state of the toggle.        this.toggled = !this.toggled;        // Set the state of the toggle image.        this.toggle.visible = this.toggled;                // Fire the toggle signal.        this.toggleSignal.dispatch(this.toggled)    }    /**     * ToggleButton::destroy. Destroys the toggle button.     */    destroy() {        // Destroy the toggle image.        this.removeChild(this.toggle);        this.toggle.destroy();        this.toggle = null;        // Destroy the toggle signal.        this.toggleSignal.removeAll();        this.toggleSignal.dispose();        this.toggleSignal = null;        // Destroy the Phaser.Button object.        super.destroy();    }}

The destroy override might be wrong. There might be a better way to destroy those components. 

Link to comment
Share on other sites

Realized this assumes that you're using an atlas. If not, change:

this.toggle = game.make.image(toggleX, toggleY, key, toggleKey);

To:

this.toggle = game.make.image(toggleX, toggleY, toggleKey);
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...