How to create a HTML5 3D flipping card animation… in 2D using Phaser

If you plan to create card games, it will come a time when you have to show covered cards, showing their backs, and then you need to flip them showing their value. Normally, with a 3D engine it would be really an easy task, as it’s just a primitive which flips along one of its axis. What to do when we aren’t using a 3D engine? We can fake the flip movement using a couple of Phaser tweens. We can zoom the card along its vertical axis, giving the feeling the card is being raised, while we shrink it along its horizontal axis until the card is just a line – that’s the moment when the card is perpendicular to the table. Then we change card frame, lower the card acting on its y scale while we enlarge it along its horizontal axis to slowly show the new frame.
Click or tap on the card to make it flip. Here is the completely commented source code, for you to play:
// the game itself
var game;

// global object with game options
var gameOptions = {

    // flipping speed in milliseconds
    flipSpeed: 200,

    // flipping zoom ratio. Simulates the card to be raised when flipping
    flipZoom: 1.2
}
window.onload = function() {

    // creation of a 500x500 pixels game
    game = new Phaser.Game(500, 500);

    // game states
    game.state.add("PlayGame", playGame);
    game.state.start("PlayGame");
}

var playGame = function(game){}
playGame.prototype = {
    preload: function(){

        // making the game cover the biggest window area possible while showing all content
        game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
        game.scale.pageAlignHorizontally = true;
        game.scale.pageAlignVertically = true;

        // changing background colors
        game.stage.backgroundColor = 0x448844;

        // card sprite sheet
        game.load.spritesheet("cards", "cards.png", 167, 243);

    },
    create: function(){

        // adding the card
        this.card =  game.add.sprite(game.width / 2, game.height / 2, "cards", 0);

        // setting card anchor points to its center
        this.card.anchor.set(0.5);

        // custom property to tell us if the card is flipping. It's not, at the moment.
        this.card.isFlipping = false;

        // waiting for player input
        game.input.onDown.add(function(){

            // if the card is not flipping...
            if(!this.card.isFlipping){

                // it's flipping now!
                this.card.isFlipping = true;

                // start the first of the two flipping animations
                this.flipTween.start();
            }
        }, this);

        // first tween: we raise and flip the card
        this.flipTween = game.add.tween(this.card.scale).to({
            x: 0,
            y: gameOptions.flipZoom
        }, gameOptions.flipSpeed / 2, Phaser.Easing.Linear.None);

        // once the card is flipped, we change its frame and call the second tween
        this.flipTween.onComplete.add(function(){
            this.card.frame = 1 - this.card.frame;
            this.backFlipTween.start();
        }, this);

        // second tween: we complete the flip and lower the card
        this.backFlipTween = game.add.tween(this.card.scale).to({
            x: 1,
            y: 1
        }, gameOptions.flipSpeed / 2, Phaser.Easing.Linear.None);

        // once the card has been placed down on the table, we can flip it again
        this.backFlipTween.onComplete.add(function(){
            this.card.isFlipping = false;
        }, this);
    }
}

Now you can add some realism to your 2D card games. Next time I will show you how to add shadows and another couple of interesting effects, meanwhile download the source code.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

215 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stairs
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers