HTML5 Totem Destroyer fully working prototype using Phaser

Read all posts about "" game

One of the frameworks I am using to release some HTML5 games is Phaser.

I already showed you how to include and use p2 physics with Phaser in the post quick HTML5 physics test with Phaser 2.0 and p2 physics, now it’s time to see something more complete and complex like a Totem Destroyer prototype.

If you are a long time reader, you should remember some old posts about this topic, like the AS3 full Totem Destroyer prototype and the complete HTML5 Totem destroyer engine using PhysicsJS.

Now it’s time to use Phaser to create the same thing.

By the end of this post, you will learn how to:

* Create static and dynamic bodies
* Attach images to bodies (actually is attach physics bodies to sprites)
* Destroy object with mouse click
* Handle collision listeners
* Use sensor bodies

Have a look at the result:

Click to destroy light-brown boxes, try to make the totem touch the ground or fly off the screen. Using sensors to detect when something is not on the screen is not the best practice available, but I needed a way to show you how to create sensors.

And this is the fully commented source code:

<!doctype html>
<html>
	<head>
    		<script src="phaser.min.js"></script>
    		<style>
    			body{margin:0}
    		</style>
    		<script type="text/javascript">
			window.onload = function() {
				
                    var game = new Phaser.Game(728,640,Phaser.CANVAS,"",{preload:onPreload, create:onCreate});
                    var totem;
					
				// THE GAME IS PRELOADING
				function onPreload() {
					game.load.image("grass", "grass.png");
					game.load.image("1x1_destroy", "1x1_destroy.png");
					game.load.image("4x1_destroy", "4x1_destroy.png");
					game.load.image("2x1_solid", "2x1_solid.png");
					game.load.image("3x1_destroy", "3x1_destroy.png");
					game.load.image("4x2_solid", "4x2_solid.png");
					game.load.image("totem", "totem.png");
                         game.load.image("sensor", "sensor.png");
				}
				
				// THE GAME HAS BEEN CREATED
				function onCreate() {
					// creation of large world bounds
					game.world.bounds = new Phaser.Rectangle(-300, 0, 1328, 640);   
					// adding P2 physics to the game
					game.physics.startSystem(Phaser.Physics.P2JS);
					// setting gravity
					game.physics.p2.gravity.y = 250;
					// building the totem
					var grass = game.add.sprite(364, 608, "grass");
					// adding "unbreakable" property to assets we do not want to be removed
					grass.unbreakable=true;
					// naming grass sprite as "grass" to recognize it later on
					grass.name="grass";
					game.physics.p2.enable(grass);
					grass.body.static=true;  
					var brick = game.add.sprite(460, 544, "1x1_destroy");	
					game.physics.p2.enable(brick); 
					brick = game.add.sprite(268, 544, "1x1_destroy");	
					game.physics.p2.enable(brick); 
					brick = game.add.sprite(364, 480, "4x1_destroy");	
					game.physics.p2.enable(brick); 
					brick = game.add.sprite(364, 416, "2x1_solid");	
					brick.unbreakable=true;
					game.physics.p2.enable(brick); 
					brick = game.add.sprite(332, 352, "3x1_destroy");	
					game.physics.p2.enable(brick); 
					brick = game.add.sprite(364, 256, "4x2_solid");	
					brick.unbreakable=true;
					game.physics.p2.enable(brick); 
					totem = game.add.sprite(364,128, "totem");
					totem.unbreakable=true;             
					game.physics.p2.enable(totem); 
                         // now adding bound sensors, just a bit out of game bounds
                         var sensor = game.add.sprite(-96,320, "sensor");
                         sensor.name="sensor";
                         game.physics.p2.enable(sensor);  
                         sensor.body.static=true;
                         sensor.body.data.shapes[0].sensor=true;
                         sensor = game.add.sprite(824,320, "sensor");
                         sensor.name="sensor";
                         game.physics.p2.enable(sensor);  
                         sensor.body.static=true;        
                         sensor.body.data.shapes[0].sensor=true;
					// listener for totem collision
					totem.body.onBeginContact.add(checkTotemCollision, this);
					// adding event listener for mousedown/touch event
					game.input.onDown.add(destroyBlock, this);
				}
				
				// MOUSE IS CLICKED
				function destroyBlock(pointer){
					// getting the block we clicked on
					var bodyClicked = game.physics.p2.hitTest(pointer.position);
					if(bodyClicked.length!=0){
						// if the body is not unbreakable...
						if(!bodyClicked[0].parent.sprite.unbreakable){
							// destroy the block
							bodyClicked[0].parent.sprite.kill();
						}
					}
				}
				
				// TOTEM IS COLLIDING ON SOMETHING
				function checkTotemCollision (body, shapeA, shapeB, equation) {
					if(body){ 
                              //check collision with the boundary sensors
                              if(body.sprite.name=="sensor"){
                                   // writing a text
                                   var style = { font: "65px Arial", fill: "#ff0044", align: "center" };
                                   var text = game.add.text(364, 90, "Oh, no!! Out of the stage", style);  
                                   text.anchor.set(0.5);
                                   totem.body.onBeginContact.remove(checkTotemCollision, this);
                              }       
						// check collision with the ground
						if(body.sprite.name=="grass"){
                                   // writing a text
                                   var style = { font: "65px Arial", fill: "#ff0044", align: "center" };
                                   var text = game.add.text(364, 90, "Oh, no!! On the floor!!", style);
                                   text.anchor.set(0.5);
                                   totem.body.onBeginContact.remove(checkTotemCollision, this);
						}
					}
				}
                    				
	    		};
		</script>
    </head>
    <body>
    </body>
</html>

Phaser and p2 are a really explosive couple, stay tuned to see what I have for you next days, meanwhile you can download the entire project, images included.

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