Create REAL explosions with Box2D – exploding objects and setting the center of explosion with mouse click

I got a lot of requests once I published how to create REAL explosions with Box2D and most of them asked for exploding objects clicking on them, setting the center of explosion with mouse pointer.

So I changed a bit the script and now you have such features, and to preserve speed I also removed all chunks whose area is too small. They just slow down the prototype with no advantage.

So that’s what you have now:

Click on any object (static or dynamic) to explode it.

And this is the uncommented, yet to be optimized script:

package {
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.events.Event;
	public class Main extends Sprite {
		private var world:b2World=new b2World(new b2Vec2(0,10),true);
		private var worldScale:int=30;
		private var laserSegment:b2Segment;
		private var drawing:Boolean=false;
		private var affectedByLaser:Vector.;
		private var entryPoint:Vector.;
		private var explodingBodies:Vector.;
		private var explosionCenterX:Number;
		private var explosionCenterY:Number;
		private var chunks:Number=5;
		private var explosionRadius:Number=50;
		public function Main() {
			debugDraw();
			addWall(320,480,640,20);
			addWall(320,0,640,20);
			addWall(0,240,20,480);
			addWall(640,240,20,480);
			addWall(320,240,200,200);
			addWall(250,110,60,60);
			addWall(390,110,60,60);
			addEventListener(Event.ENTER_FRAME, updateWorld);
			stage.addEventListener(MouseEvent.MOUSE_DOWN,mousePressed);
		}
		private function mousePressed(e:MouseEvent):void {
			var cutAngle:Number;
			explosionCenterX=mouseX;
			explosionCenterY=mouseY;
			var clickedBody:b2Body=GetBodyAtXY(new b2Vec2(explosionCenterX/worldScale,explosionCenterY/worldScale));
			explodingBodies=new Vector.();
			if (clickedBody!=null) {
				explodingBodies.push(clickedBody);
				for (var i:Number=0; i();
					entryPoint=new Vector.();
					world.RayCast(laserFired,laserSegment.p1,laserSegment.p2);
					world.RayCast(laserFired,laserSegment.p2,laserSegment.p1);
				}
			}
		}
		private function debugDraw():void {
			var debugDraw:b2DebugDraw = new b2DebugDraw();
			var debugSprite:Sprite = new Sprite();
			addChild(debugSprite);
			debugDraw.SetSprite(debugSprite);
			debugDraw.SetDrawScale(worldScale);
			debugDraw.SetFlags(b2DebugDraw.e_shapeBit|b2DebugDraw.e_jointBit);
			debugDraw.SetFillAlpha(0.5);
			world.SetDebugDraw(debugDraw);
		}
		private function addWall(pX:Number,pY:Number,w:Number,h:Number):void {
			var wallShape:b2PolygonShape = new b2PolygonShape();
			wallShape.SetAsBox(w/worldScale/2,h/worldScale/2);
			var wallFixture:b2FixtureDef = new b2FixtureDef();
			wallFixture.density=0;
			wallFixture.friction=1;
			wallFixture.restitution=0.5;
			wallFixture.shape=wallShape;
			var wallBodyDef:b2BodyDef = new b2BodyDef();
			wallBodyDef.position.Set(pX/worldScale,pY/worldScale);
			var wall:b2Body=world.CreateBody(wallBodyDef);
			wall.CreateFixture(wallFixture);
		}
		private function updateWorld(e:Event):void {
			world.Step(1/30,10,10);
			world.ClearForces();
			world.DrawDebugData();
		}
		private function laserFired(fixture:b2Fixture,point:b2Vec2,normal:b2Vec2,fraction:Number):Number {
			var affectedBody:b2Body=fixture.GetBody();
			if (explodingBodies.indexOf(affectedBody)!=-1) {
				var affectedPolygon:b2PolygonShape=fixture.GetShape() as b2PolygonShape;
				var fixtureIndex:int=affectedByLaser.indexOf(affectedBody);
				if (fixtureIndex==-1) {
					affectedByLaser.push(affectedBody);
					entryPoint.push(point);
				}
				else {
					var rayCenter:b2Vec2=new b2Vec2((point.x+entryPoint[fixtureIndex].x)/2,(point.y+entryPoint[fixtureIndex].y)/2);
					var rayAngle:Number=Math.atan2(entryPoint[fixtureIndex].y-point.y,entryPoint[fixtureIndex].x-point.x);
					var polyVertices:Vector.=affectedPolygon.GetVertices();
					var newPolyVertices1:Vector.=new Vector.();
					var newPolyVertices2:Vector.=new Vector.();
					var currentPoly:int=0;
					var cutPlaced1:Boolean=false;
					var cutPlaced2:Boolean=false;
					for (var i:int=0; i0&&cutAngle<=Math.PI) {
							if (currentPoly==2) {
								cutPlaced1=true;
								newPolyVertices1.push(point);
								newPolyVertices1.push(entryPoint[fixtureIndex]);
							}
							newPolyVertices1.push(worldPoint);
							currentPoly=1;
						}
						else {
							if (currentPoly==1) {
								cutPlaced2=true;
								newPolyVertices2.push(entryPoint[fixtureIndex]);
								newPolyVertices2.push(point);
							}
							newPolyVertices2.push(worldPoint);
							currentPoly=2;

						}
					}
					if (! cutPlaced1) {
						newPolyVertices1.push(point);
						newPolyVertices1.push(entryPoint[fixtureIndex]);
					}
					if (! cutPlaced2) {
						newPolyVertices2.push(entryPoint[fixtureIndex]);
						newPolyVertices2.push(point);
					}
					createSlice(newPolyVertices1,newPolyVertices1.length);
					createSlice(newPolyVertices2,newPolyVertices2.length);
					world.DestroyBody(affectedBody);
				}
			}
			return 1;
		}
		private function findCentroid(vs:Vector., count:uint):b2Vec2 {
			var c:b2Vec2 = new b2Vec2();
			var area:Number=0.0;
			var p1X:Number=0.0;
			var p1Y:Number=0.0;
			var inv3:Number=1.0/3.0;
			for (var i:int = 0; i < count; ++i) {
				var p2:b2Vec2=vs[i];
				var p3:b2Vec2=i+1, count:uint):Number {
			var area:Number=0.0;
			var p1X:Number=0.0;
			var p1Y:Number=0.0;
			var inv3:Number=1.0/3.0;
			for (var i:int = 0; i < count; ++i) {
				var p2:b2Vec2=vs[i];
				var p3:b2Vec2=i+1,numVertices:int):void {
			if (getArea(vertices,vertices.length)>=0.05) {
				var centre:b2Vec2=findCentroid(vertices,vertices.length);
				for (var i:int=0; iexplosionRadius) {
						distX=0;
					}
					else {
						distX=50-distX;
					}
				}
				var distY:Number=(centre.y*worldScale-explosionCenterY);
				if (distY<0) {
					if (distY<-explosionRadius) {
						distY=0;
					}
					else {
						distY=-50-distY;
					}
				}
				else {
					if (distY>explosionRadius) {
						distY=0;
					}
					else {
						distY=50-distY;
					}
				}
				distX*=0.25;
				distY*=0.25;
				worldSlice.SetLinearVelocity(new b2Vec2(distX,distY));
				explodingBodies.push(worldSlice);
			}
		}
		private function GetBodyAtXY(coordinate:b2Vec2):b2Body {
			var touchedBody:b2Body=null;
			world.QueryPoint(GetBodyCallback,coordinate);
			function GetBodyCallback(fixture:b2Fixture):Boolean {
				var shape:b2Shape=fixture.GetShape();
				var inside:Boolean=shape.TestPoint(fixture.GetBody().GetTransform(),coordinate);
				if (inside) {
					touchedBody=fixture.GetBody();
					return false;
				}
				return true;
			}
			return touchedBody;
		}
	}
}

I will post the complete tutorial once I’ll complete the final step: adding textures to explosions. If you want to try the class, you can copy/paste it in the example you can download at slicing, splitting and cutting objects with Box2D.

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