Do you like my tutorials?

Then consider supporting me on Ko-fi

Talking about Game development, HTML5, Javascript and Phaser.

Some days ago Phaser desktop and mobile HTML5 game framework has been updated to 2.0 (2.0.1 at the time of writing) introducing a whole set of new stuff including some new ways to handle physics.

One of such ways is managed by p2.js, which is gaining popularity among HTML5 game engines.

You can see p2.js in action in the post easy and fast HTML5 physics with Panda.js and p2.js physics library, and today we are creating the same thing, the classic “create a body, skin a body, click a body, remove a body” example.

Play with it:

Click on an empty spot to create a crate, or on an existing crate to destroy it.

And this is the source code, I would recommend to read create web and mobile HTML5 games with Phaser framework and create an HTML5 game like Space is Key with a lot of room for customization if you aren’t used to the framework.

<!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(720,480,Phaser.CANVAS,"",{preload:onPreload, create:onCreate});
					
				// THE GAME IS PRELOADING
				function onPreload() {
					game.load.image("crate", "crate.png");
				}
				
				// THE GAME HAS BEEN CREATED
				function onCreate() {
					// adding P2 physics to the game
					game.physics.startSystem(Phaser.Physics.P2JS);
					// setting gravity
					game.physics.p2.gravity.y = 250;
				     // adding event listener for mousedown/touch event
					game.input.onDown.add(addRemove, this);		
				}
				
				function addRemove(pointer){
					// checking for bodies under the mouse
					var bodyClicked = game.physics.p2.hitTest(pointer.position);
					if(bodyClicked.length==0){
						// creation of physics body and its graphic asset
						var crate = game.add.sprite(pointer.position.x, pointer.position.y, "crate");
						game.physics.p2.enable(crate);
					}
					else{
						// destruction of physics body and its graphic asset
						bodyClicked[0].parent.sprite.kill();
					}
				}
	    		};
		</script>
    </head>
    <body>
    </body>
</html>

And obviously you can download the source code with all required libraries. Next time, a complete Totem destroyer prototype.

Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.