Understanding HTML5 sprite animation with Phaser

Read all posts about "" game
What can make a game to be a great game, apart from game design and gameplay is the animation of the sprites. If you played computer games in stone age, you will surely remember the first Prince of Persia. It was a fair platform game, but the animation of the captive prince was awesome in 1989 – and it still rocks anyway – and made the game fly to worldwide success. While I can’t teach you how to create woderful sprite animations – my graphic skills are around “3 years old baby” level – I can show you how to manage animations in your HTML5 games with Phaser. In today’s example we have the ero taken from Jet Set Willy game, and you can make it “walk” – actually it does not move yet – by pressing Z or X keys. Try it by yourself:
Pressing X it will walk right, pressing Z it will walk left, and doing any other thing than pressing X or Z will make it stop. Remember to mantain the focus in the small game window. All starts from this sprite sheet, which I zoomed in a bit: Then, here is the fully commented source code to turn this sprite sheet into a walk animation:
<pre class="wp-block-syntaxhighlighter-code">var game;

window.onload = function() {
	game = new Phaser.Game(480, 60, Phaser.AUTO, "");
     game.state.add("PlayGame", playGame);
     game.state.start("PlayGame");
}

var playGame = function(game){};
playGame.prototype = {
     preload: function(){
          // the hero is a spritesheet with all animation frames
          game.load.spritesheet("hero", "hero.png", 20, 32);
     },
     create: function(){
          // the hero is initally placed like a normal sprite
          this.hero = game.add.sprite(game.width / 2, game.height / 2, "hero");
          // flag to determine if the hero is supposed to move right
          this.hero.goingRight = false;
          // flag to determine if the hero is supposed to move left
          this.hero.goingLeft = false;
          // default idle frame, with the hero facing right
          this.hero.idleFrame = 0;
          // this is how we set an animation, we give it a name and an array with the frames.
          var walkRightAnimation = this.hero.animations.add("walkRight", [0, 1, 2, 3]);
          var walkLeftAnimation = this.hero.animations.add("walkLeft", [4, 5, 6, 7]);
          // these are just listeners for X and Z keys
          this.rightKeyPressed = game.input.keyboard.addKey(Phaser.Keyboard.X);
          this.leftKeyPressed = game.input.keyboard.addKey(Phaser.Keyboard.Z);          
          // setting goingRight to true if X is pressed
          this.rightKeyPressed.onDown.add(function(){
               this.hero.goingRight = true;     
          }, this);
          // setting goingRight to false if X is released
          this.rightKeyPressed.onUp.add(function(){
               this.hero.goingRight = false;     
          }, this);  
          // setting goingLeft to true if Y is pressed
          this.leftKeyPressed.onDown.add(function(){
               this.hero.goingLeft = true;     
          }, this);
          // setting goingLeft to false if Y is released
          this.leftKeyPressed.onUp.add(function(){
               this.hero.goingLeft = false;     
          }, this);
     },
     update: function(){
          // if we are going left and not right (we don't want two keys to be pressed at the same time)
          if(this.hero.goingRight && !this.hero.goingLeft){
               this.hero.animations.play("walkRight", 10, true); // <- Look!! This is how I play "walkRight" animation at 10fps with looping
               // idle frame with hero facing right
               this.hero.idleFrame = 0;     
          }
          else{
               // if we are going right and not left
               if(!this.hero.goingRight && this.hero.goingLeft){
                    this.hero.animations.play("walkLeft", 10, true); // <- Look!! This is how I play "walkLeft" animation at 10fps with looping 
                    // idle frame with hero facing left
                    this.hero.idleFrame = 4;      
               }
               else{
                    // show idle frame
                    this.hero.frame = this.hero.idleFrame;         
               }
          }
     }            
}</pre>
In a few lines I animated a sprite, now it’s your turn to draw amazing animations and create the next Prince of Persia (or even better, in my opinion, Jet Set Willy) made with Phaser! 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