Phaser Animated Buttons

This post is in response to a Phaser Game Makers Group member’s question. The question arose from trying to convert a flash slot game into Phaser. Now most of us coming from flash remember that it is quite easy to make a button in flash with the IDE tool. By dragging images we were able to quickly define up, down and over states. Phaser also includes a way to define a button in this way.


In this case, what the programmer is trying to copy is a button that looks as if it is being pressed on its own, to try to draw the attention of the player into pressing it. So for this example, I will not be using a Phaser button, but instead a sprite. Now I want to stress at the start, that there are so many different ways to do this. This is simply the first one that came to mind.

I was sent two different images, but I have replaced them with my own, just for demonstration purposes, and combined them into 1 sprite sheet.

I will be using a function to make a copy of the buttons, so I can have 1 normal, and 1 animated button. You can see more about this technique in my Complex Objects Tutorial. I will also funnel all button events through 2 central functions. If this were a full game or app, I would simply make a switch statement inside the buttonPressed function.

var StateMain = {
    preload: function() {
        //load the sprite sheet
        game.load.spritesheet("buttons", "images/buttons.png", 144, 68, 2);
    create: function() {
        //just some debug text
        this.text1 = game.add.text(game.width / 2, 0, "0");
        this.text1.anchor.set(0.5, 0);
        this.text1.fill = "#ffffff";
        //create 2 buttons
        this.button1 = this.makeButton(game.width / 2, game.height * .25, 1);
        this.button2 = this.makeButton(game.width / 2, this.button1.y + this.button1.height * 1.1, 2);
        //add animation to the 2nd button
        //add more zeros to slow down the animation
        //use less zeros to speed up the animation
        this.button2.animations.add("auto", [0, 0, 0, 0, 0, 0, 1], 3, true);"auto");
     * Function to make a copy of the button template
    makeButton(xx, yy, index) {
        var button = game.add.sprite(xx, yy, "buttons");
        button.index = index;
        button.anchor.set(0.5, 0.5);
        button.inputEnabled = true;, this);, this);
        return button;
    buttonPressed(target) {
        //show the down frame
        target.frame = 1;
        this.text1.text = target.index;
    buttonReleased(target) {
        //show the up frame
        target.frame = 0;
        this.text1.text = 0;
    update: function() {}

And Here is the result

Leave a Comment