The magic of compound objects with Box2D – HTML5 version powered by Phaser

Back in 2008 I blogged about the magic of compound objects with Box2D to create complex shapes, and eventually built a game upon this concept, called MazeRoll.

Now it’s time to do the same thing with Phaser, building a maze in a single body.

The maze is built with the same script used in Pure JavaScript perfect tile maze generation – with a bit of magic thanks to Phaser, have a look at it:

Try to drag the mouse, you will see it’s a single body made with more fixtures.

Everything runs around the creation of a body with no fixtures – think about it as an empty body – with rectangular fixtures added to it at runtime with addRectangle method.

addRectangle(width, height, offsetX, offsetY, rotation)

Adds a Rectangle fixture to a Body. You can control the offset from the center of the body and the rotation. It will use the World friction, restitution and density by default.

This is the source code.

var game;
var maze = [];
var mazeWidth = 15; // maze width, in tiles. Should be odd
var mazeHeight = 11; // maze height, in tiles. Should be odd
var cellSize = 30;

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

playGame.prototype = {
  	create: function(){
  		game.stage.backgroundColor = "#222222";
  		// in the same way we initialized other Phaser physics engines, this is how we initialize Box2D engine
		game.physics.startSystem(Phaser.Physics.BOX2D);
		// setting gravity
		game.physics.box2d.gravity.y = 500;
		// adding a ground static body
    		var groundBody = new Phaser.Physics.Box2D.Body(game, null, 0, 0, 0);
          // adding a rectangle fixture to the body
          groundBody.addRectangle(640, 20, game.width/2, game.height-10); 
    		// waiting for player input
    		game.input.onDown.add(mouseDragStart, this);
          game.input.addMoveCallback(mouseDragMove, this);
          game.input.onUp.add(mouseDragEnd, this);
          //var box2d = new Phaser.Physics.Box2D(game);
          var mazeBody = new Phaser.Physics.Box2D.Body(game, null, game.width/2-mazeWidth*cellSize/2, 0, 2);
          // creation of the maze itself
          createMaze();
          for(var i = 0; i < mazeHeight; i ++){
               for(var j = 0; j < mazeWidth; j ++){
                    if(maze[i][j]){
                         // adding maze bricks
                         mazeBody.addRectangle(cellSize, cellSize, cellSize * j, cellSize * i)     
                    }
               }
          }
	},
     render: function(){
          // this is the debug draw in action
          game.debug.box2dWorld();
     }
}

function mouseDragStart() {
     game.physics.box2d.mouseDragStart(game.input.mousePointer);    
}

function mouseDragMove() {
     game.physics.box2d.mouseDragMove(game.input.mousePointer);    
}

function mouseDragEnd() {
    game.physics.box2d.mouseDragEnd();    
}

function createMaze(){
     var moves = [];
     for(var i = 0; i < mazeHeight; i ++){
          maze[i] = [];
          for(var j = 0; j < mazeWidth; j ++){
               maze[i][j] = 1;
          }
     }
     var posX = 1;
     var posY = 1;
     maze[posX][posY] = 0; 
     moves.push(posY + posY * mazeWidth);
     while(moves.length){       
          var possibleDirections = "";
          if(posX+2 > 0 && posX + 2 < mazeHeight - 1 && maze[posX + 2][posY] == 1){
               possibleDirections += "S";
          }
          if(posX-2 > 0 && posX - 2 < mazeHeight - 1 && maze[posX - 2][posY] == 1){
               possibleDirections += "N";
          }
          if(posY-2 > 0 && posY - 2 < mazeWidth - 1 && maze[posX][posY - 2] == 1){
               possibleDirections += "W";
          }
          if(posY+2 > 0 && posY + 2 < mazeWidth - 1 && maze[posX][posY + 2] == 1){
               possibleDirections += "E";
          } 
          if(possibleDirections){
               var move = game.rnd.between(0, possibleDirections.length - 1);
               switch (possibleDirections[move]){
                    case "N": 
                         maze[posX - 2][posY] = 0;
                         maze[posX - 1][posY] = 0;
                         posX -= 2;
                         break;
                    case "S":
                         maze[posX + 2][posY] = 0;
                         maze[posX + 1][posY] = 0;
                         posX += 2;
                         break;
                    case "W":
                         maze[posX][posY - 2] = 0;
                         maze[posX][posY - 1] = 0;
                         posY -= 2;
                         break;
                    case "E":
                         maze[posX][posY + 2]=0;
                         maze[posX][posY + 1]=0;
                         posY += 2;
                         break;         
               }
               moves.push(posY + posX * mazeWidth);     
          }
          else{
               var back = moves.pop();
               posX = Math.floor(back / mazeWidth);
               posY = back % mazeWidth;
          }                                 
     }      
}

And this is how you can create compound objects with Box2D and Phaser. Next time, I will port my MazeRoll game in HTML5, 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