Adding a Toast Message in Phaser

A toast message is a text message that fades in and out. It is named a toast message because it is similar to someone raising a glass, making a toast and then lowering the glass again. It gets your attention without interrupting the experience.

Here is an example

The Code

var StateMain = {
    preload: function() {
        game.load.image("toastBack", "images/back.png");
        game.load.image("btnToast", "images/btnGenerate.png");
    },
    create: function() {

        //SET UP TEST BUTTON
    	this.btnToast=game.add.sprite(game.world.centerX,game.height*.25,"btnToast");
    	this.btnToast.anchor.set(0.5,0.5);
    	this.btnToast.inputEnabled=true;
    	this.btnToast.events.onInputDown.add(this.testToast,this);
    },
    testToast: function() {
        this.btnToast.visible=false;
        //get an instance of a toast object 
        //and place it in postion
        var toast = this.makeToast("TEST!");
        toast.x = game.world.centerX;
        toast.y = game.world.height * .8;
        //fade in the toast object
        this.fadeIn(toast);
    },
    makeToast: function(message) {
        var toastGroup = game.add.group();
        var toastText = game.add.text(0, 0, message);
        var toastBack = game.add.sprite(0, 0, "toastBack");
        toastBack.width = game.width * .9;
        //
        //
        //SET ANCHORS
        toastText.anchor.set(0.5, 0.5);
        toastBack.anchor.set(0.5, 0.5);
        //
        //ADD THE TEXT AND SPRITE GRAPHIC TO THE TOAST GROUP
        toastGroup.add(toastBack);
        toastGroup.add(toastText);
        toastGroup.alpha = 0;
        //
        return toastGroup;
    },
    fadeIn: function(obj) {
        var tween = game.add.tween(obj).to({
            alpha: 1
        }, 1000, Phaser.Easing.Linear.None, true);
        tween.onComplete.add(this.delay, this);
    },
    delay:function(obj)
    {
        //WHEN TWEEN IS DONE PAUSE HERE FOR DELAY
        //SET A FADE OBJECT IN THE SCOPE OF THE STATE,
        //SINCE WE CAN NOT PASS THE OBJECT IN THE TIMER
    	this.fadeObj=obj;
    	game.time.events.add(Phaser.Timer.SECOND*2, this.delayDone, this);
    },
    delayDone:function()
    {
        //NOW THAT DELAY IS DONE CALL FADE OUT
    	this.fadeOut(this.fadeObj);
    },
    fadeOut: function(obj) {
        var tween = game.add.tween(obj).to({
            alpha: 0
        }, 1000, Phaser.Easing.Linear.None, true);
        tween.onComplete.add(this.fadeDone, this);
    },
    fadeDone:function()
    {
        this.btnToast.visible=true;
    },
    update: function() {}
}

Source Code

Leave a Reply

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