Creating Dynamic Button Class In PIXI JS

 

Creating Dynamic Button Creation Class In PIXI JS

-In this tutorial we will go over how to dynamically create buttons using a Button class.

What we will cover:

  • How to create and import a button class into our game state to create buttons on the fly

 

To note I am using TypeScript for this project, however it should conform easily to regular written javascript as well. I am also using a custom PIXI project that I use for personal use, so some syntax may need to be adjusted to work for how your project is set up.

 

Building Our Standalone Button Class:



export default class Button extends PIXI.Sprite {

    private _text: PIXI.Text;

    private _cb: Function;

    constructor(x: number, y: number, width: number, height: number) {
        super();
        this.create(x, y, width, height);
    }

    create(x: number, y: number, width: number, height: number) {
        // generate the texture
        let gfx = new PIXI.Graphics();
        gfx.beginFill(0xffffff, 1);
        gfx.drawRoundedRect(0, 0, width, height, height / 5);
        gfx.endFill();
        this.texture = gfx.generateCanvasTexture();

        // set the x, y and anchor
        this.x = x;
        this.y = y;
        this.anchor.x = 0.5;
        this.anchor.y = 0.5;

        // create the text object
        this._text = new PIXI.Text("", 'arial');
        this._text.anchor = new PIXI.Point(0.5, 0.5);
        this.addChild(this._text);

        // set the interactivity to true and assign callback functions
        this.interactive = true;

        this.on("mousedown", () => {
            this.onDown();
        }, this);

        this.on("mouseup", () => {
            this.onUp();
        }, this);

        this.on("mouseover", () => {
            this.onHover();
        }, this);

        this.on("mouseout", () => {
            this.onOut();
        }, this);
    }

    public setText(val: string, style?: PIXI.TextStyle) {
        // Set text to be the value passed as a parameter
        this._text.text = val;
        // Set style of text to the style passed as a parameter
        this._text.style = style;
    }

    private onDown() {
        console.log('Clicked');
        this.y += 5;
        this.tint = 0xffffff;
    }

    private onUp() {
        console.log('onup');
        if(typeof(this._cb) === 'function') {
            this._cb();
        }
        this.y -= 5;
        this.tint = 0xF8A9F9;
    }

    private onHover() {
        console.log('On Hover');
        this.tint = 0xF8A9F9;
        this.scale.x = 1.2;
        this.scale.y = 1.2;
    }

    private onOut() {
        console.log('On Out');
        this.tint = 0xffffff;
        this.scale.x = 1;
        this.scale.y = 1;
    }

    public get clicked() {
        return this._cb;
    }

    public set clicked(cb: Function) {
        this._cb = cb;
    }


}

Lets Break This Down:

  • We begin by setting up our class exporting default class Button to be imported and called somewhere else(in our case game state). This class with extend PIXI.Sprite capabilities.
  • Next we set up our one non local variable for this class which is _text and is type PIXI.Text. We also set a non local variable for a callback function we will be using later as type function.

  • We then setup our constructor function which will accept parameters X, Y, Width, and Height. Inside our constructor function we will call our create function which also accepts X, Y, Width, and Height.

  • Then we move to our create function which also accepts the same parameters as our constructor and our class itself. We begin by creating our graphics object that will be the texture for our button using PIXI.Graphics(). We begin our fill stating it will be color white, and have an alpha of 1. We state this graphics object will be a rounded rectangle and we pass in our parameters in our case they are going to be passed with variables from our constructor when we
    instantiate.

  • We continue by setting the X and Y of our class using this.x, this.y and setting these to X, and Y which will be passed when instantiated.

  • Afterwards we create our text in our previously defined variable this._text, it is a new PIXI.Text and the parameters we pass are an open string(we will override later to make this dynamic), and our default font-family which is arial. We then set the anchor of our text object to be 0.5 x and y and we add the text object to the class as a child.

  • We also set this.interactive to true seeing as we always want our button to be interactive.

  • Then we declare a public variable called setText with two parameters val which will be a string will pass when the button is created to be able to dynamically create the text for our button. As well as an optional parameter called style which will be of type PIXI.TextStyle.

  • Inside of this function we will set our original text variables text to be equal to val(whatever string we pass when we call the function), as well as the text.style to be equal to the style we pass IF we decide we want a style.

  • We then move on to create different functionality for our button by calling this.on() we have 4 different ones with 4 different key strings “mousedown”, “mouseup”, “mouseover”, “mouseout”. Whenever one of these is triggered it will alter different aspects of the button such as Y placement and will also call a corresponding function to do things such as change the tint of the scale.

  • We also create a public GETTER and SETTER for our callback function.

Setting Up Our GameState To Use Our New Button Class:

  • Please note in my project build for PIXI I am using a custom setup where we have written our own custom State Manager, thus why our GameState extends State. This will most likely be different depending on how you have your project set up.


import Button from './../Objects/Button';

export default class State extends PIXI.Container {

    private _button:Button;
    private _renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer;

    constructor() {
        super();
    }

     create() {
        this._button = new Button(this._renderer.width * 0.5, 
        this._renderer.height * 0.5, 150, 75);

        let style = new PIXI.TextStyle({
            fontFamily: 'Arial', // Font Family
            fontSize: 22, // Font Size
            fontStyle: 'italic',// Font Style
            fontWeight: 'bold', // Font Weight
            fill: ['#ffffff', '#F8A9F9'], // gradient
            stroke: '#4a1850',
            strokeThickness: 5,
            dropShadow: true,
            dropShadowColor: '#000000',
            dropShadowBlur: 4,
            dropShadowAngle: Math.PI / 6,
            dropShadowDistance: 6,
            wordWrap: true,
            wordWrapWidth: 440
        });

        this._button.setText("Play!", style);

        this.addChild(this._button);

        this._button.clicked = () => {
            console.log('I am clicked');
        }
    }
}

  • First we begin by importing our button class from wherever we have saved it in our directory.

  • Then we begin by creating a variable to hold our button and declare it will always be type Button which we have imported from our button class. We also create a variable called _renderer to house our renderers functionality.

  • Next we begin building what we want in our create function. First off by instantiating our button with our variable this._button, we pass in our parameters we want for this button that were defined in our Button class.

  • We then create a local variable called style which is a new PIXI.TextStyle, we pass our preferred parameters. If you have not worked with PIXI.TextStyle before I recommend taking a look at the docs found here http://pixijs.download/dev/docs/PIXI.TextStyle.html

  • Afterwards we call this._button.setText() and pass in our parameters in my case for the value I passed “Play!” and for style we have passed our variable called style that we declared beforehand.

  • Finally we add the button as a child to our GameState, as well as write the corresponding functions to go with the click/hover functionality of our button.

  • We also add a lexical function for when our button has been clicked to trigger our callback functionality.

Voila! We have created a custom button class that is dynamic!

If all has gone well and you have followed this line by line you should see something like this on your screen.

Screen Recording

Conclusion:

  • We learned how to create a custom dynmaic button class that can be instantiated across different states.
  • We greated a custom public setText function to dynamically create the text and style for individual buttons.
  • We took a quick and basic look at different click/hover functions and how to make our buttons a bit more interactive.

Thank you very much for reading. Please stay tuned for upcoming tutorials.

Twitter

Error code 89: Invalid or expired token.

Stay Updated