38 Phaser Buttons

38 Phaser Buttons

When I’m making a quick game or a test, I don’t want to have to take the time to make separate custom buttons. ┬áMost of the time I’ll just make a quick text button that I can use to make as many buttons as I need. You can see how to make your own in this post Making Complex Objects

You can use these buttons a temporary or permanent part of your game’s UI.

How To Use

These instructions assume you are using a folder called images for your games images and the javascript is placed in a folder called js

  1. Copy images/buttons folder to your images folder
  2. Copy the js/classes folder to your js folder
  3. Copy this line to your index HTML file

4. Preload the button style you want to use (see sets and styles below)

TextButton.preload(set, style);

For example:

TextButton.preload(1, 4);

5. In your create function make the button

Create the button

Use the following format

var button = new TextButton(text, set,style, pressed_callback);

For example

var button = new TextButton('press me!', 1, 4, this.buttonPressed);

You can also set the size and color

var button = new TextButton(text, set,style, pressed_callback, text_size, textColor);

var button2 = new TextButton('Turbo Boost', 3, 5, this.buttonPressed, 11, "#ffffff");

You can also set the properties separately

var button3 = new TextButton('Red Alert', 2, 1);
button3.x = game.width / 2;
button3.y = 300;
button3.setTextSize(8);
button3.setTextColor("#121212");
button3.setTextPos(0, -5);
button3.setCallBack(this.buttonPressed);

Here is a full example:

var StateMain = {
    preload: function() {

    	TextButton.preload(1,4);
    	TextButton.preload(2,1);
    	TextButton.preload(3,5);
    },
    create: function() {
    	//
    	//
    	//
    	//
        var button = new TextButton('press me!', 1, 4, this.buttonPressed);
        button.x = game.width/2;
        button.y = 100;
        //
        //
        //
        //
        var button2 = new TextButton('Turbo Boost', 3, 5, this.buttonPressed, 11, "#ffffff");
      	button2.x = game.width/2;
        button2.y = 200;
        //
        //
        //
        var button3 = new TextButton('Red Alert', 2, 1);
        button3.x = game.width/2;
        button3.y = 300;
        button3.setTextSize(8);
        button3.setTextColor("#121212");
        button3.setTextPos(0,-5);
        button3.setCallBack(this.buttonPressed);
    },
    buttonPressed(target)
    {
    	alert(target.getText());
    },
    update: function() {}
}

And the result

Set 1

Set 2

Set 3