Card Flip Animation in Phaser

The code example below shows how a simple card flip animation can be achieved in Phaser. In order to flip or rotate a card around x-axis we need to set the scale to zero, change the sprite frame and then set the scale back to one.

TheGame.MyGame.prototype = {
    preload: function () {
    },
    create: function () {
		this.card = this.add.sprite(this.world.centerX, this.world.centerY, "card")
		this.card.frame = 0;
		this.card.anchor.setTo(0.5);
		// roll the dice when a mouse button is clicked
		this.game.input.onDown.add(this.flipCard, this);
    },
	flipCard: function () {
		var tween1 = this.game.add.tween(this.card.scale);
	    tween1.to({ x: 0 }, 300, Phaser.Easing.Linear.None, false, 0);
	    tween1.onComplete.addOnce(function (sprite, tween) {
			if(this.card.frame == 0)
	            this.card.frame = 1;
		    else
		        this.card.frame = 0;
	    }, this);
	    var tween2 = this.game.add.tween(this.card.scale);
	    tween2.to({ x: 1 }, 300, Phaser.Easing.Linear.None, false, 0);
	    tween1.chain(tween2);
	    tween1.start();	
	}
};

This example flips the card around x-axis. In order to flip it around y-axis, change as following

	flipCard: function () {
		var tween1 = this.game.add.tween(this.card.scale);
	    tween1.to({ y: 0 }, 300, Phaser.Easing.Linear.None, false, 0);
	    tween1.onComplete.addOnce(function (sprite, tween) {
			if(this.card.frame == 0)
	            this.card.frame = 1;
		    else
		        this.card.frame = 0;
	    }, this);
	    var tween2 = this.game.add.tween(this.card.scale);
	    tween2.to({ y: 1 }, 300, Phaser.Easing.Linear.None, false, 0);
	    tween1.chain(tween2);
	    tween1.start();		
	}

Click here to run the example on your system.


Leave A Comment

Your email address will not be published.