Phaser Tutorial: create a HTML5 prototype of the iOS game “Dashy Panda”

Read all posts about "" game

Did you play Appsolute GamesDashy Panda?

It’s an endless runner with a Panda looking for rice bowls and avoiding spikes. When you touch the screen the Panda walks, when you release the screen the panda stops.

dashy

Very basic gameplay like in all endless runner games, a genre which is gaining a lot of popularity as written in this post, and there’s even an entire minibook about the making of this genre of games.

Like in most endless runner games, the character controlled by the player does not actually “run”, as it remains in a fixed position while the whole environment runs towards the character.

There are basically two features which are really interesting in the prototype we are about to build:

1) The panda isn’t completely immovable but it actually walks for a certain amount of pixels before stopping and having the environment run towards it

2) The spikes, the only deadly enemy at the moment, appear from the ground in a well randomized way, as they have random placement, raise to a random height at a random speed, then remain underground for a random amount of time.

Believe it or not, we will be able to develop the entire spike thing using only one tween. Tween management is a Phaser key feature, I was able to create an entire game only using tweens.

This is what we have at the moment:

Tap/click and hold to make the panda walk, release to make it stop, do not touch spikes. Controlling the panda may be a little confusing at the moment because you don’t have antyhing but deadly spikes moving, so probably you won’t be able to see the spikes before you die, anyway the game will get better with next update and you should focus on spikes creation and animation at the moment.

Here is the source code:

var game;

// panda speed, in pixels per second
var pandaSpeed = 200;

// panda max horizontal movement before the game scrolls
var pandaXLimit = 160;

// pixels range between a spike and next spike
var spikeGap = [70,200];

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

var playGame = function(game){};

playGame.prototype = {
     preload: function(){
           game.load.image("ground", "ground.png");
           game.load.image("panda", "panda.png");
           game.load.image("spike", "spike.png");
     },
     create: function(){
          // group which will contain all spikes 
          this.spikeGroup = game.add.group();
          game.stage.backgroundColor = "#6cc9bf";
          game.add.image(0, game.height - 40, "ground");
          this.panda = game.add.sprite(40, game.height - 40, "panda");
          this.panda.anchor.set(0.5, 1);
          // the panda can move only until it reaches pandaXLimit. Then the
          // whole game will move towards the panda
          this.panda.canMove = true;
          // isMoving tells if the panda or the whole game are moving. In other
          // words if the player wants to move the panda, no matter what is
          // actually being moved
          this.panda.isMoving = false;
          // adding the panda to ARCADE physics system
          game.physics.enable(this.panda, Phaser.Physics.ARCADE);
          // moving the panda when an input is pressed
          game.input.onDown.add(this.movePanda, this);
          // stopping the panda when an input is released
          game.input.onUp.add(this.stopPanda, this);
          // the first spike is added in the middle of the canvas
          this.addSpike(game.width / 2);
     },
     movePanda: function(){
          // the idea is: if the panda can move, then move the panda, else
          // move all spikes towards the panda. Then set isMoving to true
          if(this.panda.canMove){
               this.panda.body.velocity.x = pandaSpeed; 
          }
          else{
               for(var i = 0; i < this.spikeGroup.length; i++){
                    this.spikeGroup.getChildAt(i).body.velocity.x = -pandaSpeed;     
               }
          } 
          this.panda.isMoving = true; 
     },
     stopPanda: function(){
          // the idea is: stop the panda and all spikes, set isMoving to false
          this.panda.body.velocity.x = 0; 
          for(var i = 0; i < this.spikeGroup.length; i++){
               this.spikeGroup.getChildAt(i).body.velocity.x = 0;     
          } 
          this.panda.isMoving = false;
     },
     addSpike: function(posX){
          // to add a spike we will create a new Spike instance, assigning it
          // a velocity if the panda is moving
          var spike = new Spike(game, posX);
          game.add.existing(spike);
          if(this.panda.isMoving){
               spike.body.velocity.x = - pandaSpeed;
          }
          // each spike is added to the group
          this.spikeGroup.add(spike);
          // this will recursively add new spikes until there are enough spikes
          // to cover at least twice the screen width
          if(posX < game.width * 2){
               posX = posX + game.rnd.between(spikeGap[0], spikeGap[1]);
               this.addSpike(posX);     
          }
     },
     update: function(){
          // this is how I make the panda stop when it reaches its maximum
          // horizontal position and start moving the environment instead
          if(this.panda.canMove && this.panda.x > pandaXLimit){
               this.panda.canMove = false; 
               this.panda.body.velocity.x = 0;  
               this.movePanda();       
          }
          // the child with the highest index in spikeGroup group is the latest
          // added spike, which is always the righmost. I am checking if we are 
          // running out of spikes by checking its position, and adding new spikes
          // if needed
          if(this.spikeGroup.getChildAt(this.spikeGroup.length - 1).x < game.width){
               this.addSpike(game.width + game.rnd.between(spikeGap[0], spikeGap[1]));       
          }
          // making the game restart if the panda hits a spike
          game.physics.arcade.collide(this.panda, this.spikeGroup, null, function(s, b){
               game.state.start("PlayGame");     
          }, this);
     }
}

Spike = function (game, posX) {
	Phaser.Sprite.call(this, game, posX, game.height - game.rnd.between(0, 40), "spike");
	game.physics.enable(this, Phaser.Physics.ARCADE);
     this.anchor.set(0, 1);
     this.body.immovable = true;
     // this is the core of the class: the tween which handles spike movement.     
     game.add.tween(this).to({
          y: game.height + 20
     }, 150 + game.rnd.between(0, 50), Phaser.Easing.Quintic.In, true, 0, -1).yoyo(true, game.rnd.between(600, 1200)); 
     // this is how it works:
     // 1 - The spike starts outside the terrain at a random height
     // 2 - The tween itself makes it completely disappear into the terrain at a random speed
     // 3 - The Quintic easing makes the movement not linear
     // 4 - The movement is repeated forever
     // 5 - There is a yoyo effect with a random delay. Such delay is when your panda can safely pass   
};

Spike.prototype = Object.create(Phaser.Sprite.prototype);
Spike.prototype.constructor = Spike;

Spike.prototype.update = function(){
     if(this.x < -40){
          this.destroy();
     }
}

As you can see, spikes have quite a great randomness, just like the original game. Next time, I’ll show you how to collect rice bowls and a nice scrolling background, 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