Create a HTML5 level select screen controlled by swipe – new feature: actually selecting a level

Some days ago I published the post Create a HTML5 level select screen controlled by swipe without actually checking for swipes and I think you are wondering how to make these thumbnails act like a button to let the player actually be able to select a level. If you simply turn thumbnails images into buttons, it won’t work because the transparent draggable layer is placed over the buttons, making them unreachable. Phaser also features a property called priorityID to determine which game objects should get priority when input events occur. For example if you have several Sprites that overlap, by default the one at the top of the display list is given priority for input events. You can stop this from happening by controlling the priorityID value. The higher the value, the more important they are considered to the Input events. So you may think to assign the buttons an higher priorityID value in order to trig them when the player is pressing them. This would work, but players won’t be allowed anymore to drag level selection screen if the input is over a button. It would trigger the button instead. The method I used checks, once the drag stopped, if the player actually dragged something. If at the end of an input no dragging occurred, then I suppose it wasn’t a drag, it was a click/tap. At this time, I only need to check for input coordinates to be inside a thumbnail bounding box and the magic is done. Check the example:
You can drag, swipe and select levels. All in one. Look at the source code:
var game;
// colors is actually the array of level pages
var colors = ["0xac81bd","0xff5050","0xdab5ff","0xb5ffda","0xfffdd0","0xcc0000","0x54748b","0x4b0082","0x80ab2f","0xff784e","0xe500db","0x223c4a","0x223c4a","0xf1290e","0x648080","0xbbc1c4","0x6f98a2","0x71717e"];
// columns of thumbnails in each page
var columns = 3;
// rows of thumbnails in each page
var rows = 4;
// thumbnail width, in pixels
var thumbWidth = 60;
// thumbnail height, in pizels
var thumbHeight = 60;
// empty space between two thumbnails, in pixels
var spacing = 20;

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

var playGame = function(game){};
playGame.prototype = {
     preload: function(){
          game.load.image("levelthumb", "levelthumb.png");
          game.load.image("transp", "transp.png");
     },
     create: function(){  
          game.stage.backgroundColor = "#000044"; 
          this.pageText = game.add.text(game.width / 2, 16, "Swipe to select level page (1 / " + colors.length + ")", {font: "18px Arial", fill: "#ffffff"})
          this.pageText.anchor.set(0.5);
          this.scrollingMap = game.add.tileSprite(0, 0, colors.length * game.width, game.height, "transp");
          this.scrollingMap.inputEnabled = true;
          this.scrollingMap.input.enableDrag(false);
          this.scrollingMap.input.allowVerticalDrag = false;
          this.scrollingMap.input.boundsRect = new Phaser.Rectangle(game.width - this.scrollingMap.width, game.height - this.scrollingMap.height, this.scrollingMap.width * 2 - game.width, this.scrollingMap.height * 2 - game.height);
          this.currentPage = 0;
          var rowLength = thumbWidth * columns + spacing * (columns - 1);
          var leftMargin = (game.width - rowLength) / 2;
          var colHeight = thumbHeight * rows + spacing * (rows - 1);
          console.log(colHeight);
          var topMargin = (game.height - colHeight) / 2;
          for(var k = 0; k < colors.length; k++){
               for(var i = 0; i < columns; i++){
                    for(var j = 0; j < rows; j++){
                         var thumb = game.add.image(k * game.width + leftMargin + i * (thumbWidth + spacing), topMargin + j * (thumbHeight + spacing), "levelthumb");
                         thumb.tint = colors[k];
                         thumb.levelNumber = k * (rows * columns) + j * columns + i;
                         var levelText = game.add.text(0, 0, thumb.levelNumber, {font: "36px Arial", fill: "#000000"})
                         thumb.addChild(levelText);
                         this.scrollingMap.addChild(thumb);
                    }
               }
          }
          this.scrollingMap.events.onDragStart.add(function(){
               this.scrollingMap.startPosition = this.scrollingMap.x;
          }, this);
          this.scrollingMap.events.onDragStop.add(function(event, pointer){
               if(this.scrollingMap.startPosition == this.scrollingMap.x){
                    for(i = 0; i < this.scrollingMap.children.length; i++){
                         var bounds = this.scrollingMap.children[i].getBounds();     
                         if(bounds.contains(pointer.x, pointer.y)){
                              alert("Play level " + this.scrollingMap.children[i].levelNumber);
                              break; 
                         }                  
                    }
               }
               else{
                    if(this.scrollingMap.startPosition - this.scrollingMap.x &gt; game.width / 8){
                         this.changePage(1);
                    }
                    else{
                         if(this.scrollingMap.startPosition - this.scrollingMap.x < - game.width / 8){
                              this.changePage(-1);
                         }
                         else{
                              this.changePage(0);
                         }
                    }
               }
          }, this);
     },
     changePage: function(page){
          this.currentPage += page;
          this.pageText.text = "Swipe to select level page (" + (this.currentPage + 1).toString() + " / " + colors.length + ")"; 
          var tween = game.add.tween(this.scrollingMap).to({
               x: this.currentPage * -game.width    
          }, 300, Phaser.Easing.Cubic.Out, true);
     }
}
Now the last feature to add is a shortcut to jump to a given page without having to swipe page by page. We’ll see how to do it next time, when I’ll also explain the whole source code. Meanwhile download the project.

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