Creation of the engine behind “Cube Jump” iOS game with Phaser

Read all posts about "" game
Did you play Cube Jump? All you have to do is help your cube travel through space. Jump on moving platforms and avoid falling. This is just another “endless runner” game and although it’s really basic, you may think you will need a 3D engine like Unity to create a game like this. That’s wrong, since it’s just isometric, we can do the same game with a 2D framework like Phaser. At the moment all we need is a sprite sheet with the three platform types: In this image I used a black background but the original uses a transparent background. Then, I just have to place the platforms on the screen, move them in a 30 degrees direction, and we have the engine ready for a cube to jump on it:
Each platform has been given a tint color. In the source code – fully commented of course – there are some hard-coded values, especially for platform position and delays, which you will need to change if you want to adjust the gameplay, but I would say the engine does its job:
// the game itself
var game;

// when the window loads...
window.onload = function() {
     // creation of a new Phaser.Game instance. Width: 320px, height: 640px;	
	game = new Phaser.Game(320, 640);
     // creation of a new Phaser state called "PlayGame"
	game.state.add("PlayGame", playGame)
     // starting "PlayGame" state;
	game.state.start("PlayGame");	
}

// PlayGame state
var playGame = function(game){}
playGame.prototype = {
	preload: function(){
          // loading the sprite sheet with all platforms
          game.load.spritesheet("platforms", "platforms.png", 346, 258);     	
	},
	create: function(){
          // placing seven platforms on the canvas
          for(var i = 0; i < 7; i++){
               addPlatform(i, game.rnd.between(0, 2));     
          }
	}
}

// addPlatform function, the core of the script. Arguments: posY -&gt; vertical position; size -&gt; platform size
function addPlatform(posY, size){
     // array with possible platform colors
     var platformColors = ["0xff0000", "0x00ff00", "0x0000ff", "0xffff00", "0xff00ff", "0x00ffff"];
     // minimum delay between the creation of the current platform and the creation of next platform, according to platform size.
     // index recap
     // 0: minimum delay after a one-sized platform
     // 1: min delay after a two-sized platform
     // 2: min delay after a three-sized platform
     var delayArray = [520, 840, 1160];    
     // this array contains the x and y coordinates of the initial and final platform position
     // index recap
     // 0 start x coordinate
     // 1 start y coordinate
     // 2 end x coordinate
     // 3 end y coordinate
     var startEndArray = [500, -300 + posY * 120, 500 - 800 * Math.cos(Math.PI/6), -300 + posY * 120 + 800 * Math.sin(Math.PI/6)];
     // startX is startEndArray[0] or startEndArray[2] according to posY value
     var startX = startEndArray[0 + 2 * (posY % 2)];
     // startY is startEndArray[1] or startEndArray[3] according to posY value
     var startY = startEndArray[1 + 2 * (posY % 2)];
      // endX is startEndArray[0] or startEndArray[2] according to posY value
     var endX = startEndArray[2 - 2 * (posY % 2)];
     // endY is startEndArray[1] or startEndArray[3] according to posY value
     var endY = startEndArray[3 - 2 * (posY % 2)]; 
     // placing the platform itself
     var platform = game.add.sprite(startX, startY, "platforms");
     // showing the proper frame
     platform.frame = size;
     // scaling the platform
     platform.scale.setTo(0.5); 
     // tinting the platform with a random color
     platform.tint = platformColors[game.rnd.between(0, platformColors.length-1)];
      // determining next platform size
     var nextPlatform = game.rnd.between(0, 2);  
     // tween to make the platform move from the starting point to the end point 
     var platformTween = game.add.tween(platform).to({
          x: endX,
          y: endY,
     }, 5000, Phaser.Easing.Linear.None, true);
     // when the easing is complete, then destroy the platform
     platformTween.onComplete.add(function(p){
          p.destroy();
     })
     // wait for the minimum delay + a random delay before placing another platform.
     // the way I choose the delay from delayArray varies according to platform direction
     if(posY % 2 == 0){
          game.time.events.add(delayArray[platform.frame] + game.rnd.between(100, 250), function(){
               addPlatform(posY, nextPlatform);
          });
     }
     else{
          game.time.events.add(delayArray[nextPlatform] + game.rnd.between(100, 250), function(){
               addPlatform(posY, nextPlatform);
          });     
     }
}
Next time I will show you how to make the player jump on platforms, meanwhile if you have questions about the code leave a comment. You can also download the full 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

214 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
// 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