Simulating mud/slime with Box2D, bitmaps and filters

This is an attempt to simulate something like mud/slime with Box2D for a game concept I am trying do develop.

I won’t go much in detail with the tutorial because at the moment I am still fine-tuning the effect, but I am showing you a step by step process to achieve a slime-looking effect.

First, let’s create some static objects:

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	public class Main extends Sprite {
		private var world:b2World=new b2World(new b2Vec2(0,5),true);
		private var worldScale:Number=30;
		public function Main() {
			debugDraw();
			var polygonShape:b2PolygonShape = new b2PolygonShape();
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.restitution=0;
			fixtureDef.density=1;
			fixtureDef.friction=0.4;
			var bodyDef:b2BodyDef= new b2BodyDef();
			bodyDef.position.Set(320/worldScale,240/worldScale);
			var container:b2Body;
			container=world.CreateBody(bodyDef);
			polygonShape.SetAsOrientedBox(132/worldScale/2,12/worldScale/2,new b2Vec2(0/worldScale,144/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			polygonShape.SetAsOrientedBox(12/worldScale/2,200/worldScale/2,new b2Vec2(-60/worldScale,0/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			polygonShape.SetAsOrientedBox(12/worldScale/2,276/worldScale/2,new b2Vec2(60/worldScale,0/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			addEventListener(Event.ENTER_FRAME,update);
		}
		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 update(e:Event):void {
			world.Step(1/30,6,2);
			world.ClearForces();
			world.DrawDebugData();
		}
	}
}

I am just creating some kind of container with a hole in the bottom.

Then, I skin the container with a transparent image and create one little ball at every frame, someone would call them particle. I remove them when they leave the stage to the bottom, and I don’t place more than 200 balls at the same time, although I was able to place about 300 of them without stressing that much my CPU.

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	public class Main extends Sprite {
		private var world:b2World=new b2World(new b2Vec2(0,5),true);
		private var worldScale:Number=30;
		public function Main() {
			debugDraw();
			var backgroundImage:BackgroundImage=new BackgroundImage();
			addChild(backgroundImage);
			var polygonShape:b2PolygonShape = new b2PolygonShape();
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.restitution=0;
			fixtureDef.density=1;
			fixtureDef.friction=0.4;
			var bodyDef:b2BodyDef= new b2BodyDef();
			bodyDef.position.Set(320/worldScale,240/worldScale);
			var container:b2Body;
			container=world.CreateBody(bodyDef);
			polygonShape.SetAsOrientedBox(132/worldScale/2,12/worldScale/2,new b2Vec2(0/worldScale,144/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			polygonShape.SetAsOrientedBox(12/worldScale/2,200/worldScale/2,new b2Vec2(-60/worldScale,0/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			polygonShape.SetAsOrientedBox(12/worldScale/2,276/worldScale/2,new b2Vec2(60/worldScale,0/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			addEventListener(Event.ENTER_FRAME,update);
		}
		private function addCircle(pX:Number,pY:Number,h:Number):void {
			var circleShape:b2CircleShape = new b2CircleShape(h/worldScale);
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.density=3;
			fixtureDef.friction=0.4;
			fixtureDef.restitution=0;
			fixtureDef.shape=circleShape;
			var bodyDef:b2BodyDef = new b2BodyDef();
			bodyDef.type=b2Body.b2_dynamicBody;
			bodyDef.position.Set(pX/worldScale,pY/worldScale);
			bodyDef.userData=new WaterCircle();
			var box:b2Body=world.CreateBody(bodyDef);
			box.CreateFixture(fixtureDef);
		}
		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 update(e:Event):void {
			var waterParticles:Number=0;
			world.Step(1/30,6,2);
			world.ClearForces();
			for (var b:b2Body = world.GetBodyList(); b; b = b.GetNext()) {
				if (b.GetUserData()!=null) {
					waterParticles++;
					if (b.GetPosition().y*worldScale>480) {
						world.DestroyBody(b);
					}
				}
			}
			if (waterParticles<300) {
				addCircle(320+1-Math.random()*2,-10,5);
			}
			world.DrawDebugData();
		}
	}
}

At this time I have a continuous flux of balls falling down the container.

Next steps consists in rendering balls on a separate DisplayObject using a Bitmap

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.display.BitmapData;
	import flash.display.Bitmap;
	import flash.geom.Matrix;
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	public class Main extends Sprite {
		private var world:b2World=new b2World(new b2Vec2(0,5),true);
		private var worldScale:Number=30;
		private var waterBitmapData:BitmapData=new BitmapData(640,480,false,0xFF333333);
		private var waterBitmap:Bitmap=new Bitmap(waterBitmapData);
		private var waterMatrix:Matrix=new Matrix();
		public function Main() {
			addChild(waterBitmap);
			var backgroundImage:BackgroundImage=new BackgroundImage();
			addChild(backgroundImage);
			var polygonShape:b2PolygonShape = new b2PolygonShape();
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.restitution=0;
			fixtureDef.density=1;
			fixtureDef.friction=0.4;
			var bodyDef:b2BodyDef= new b2BodyDef();
			bodyDef.position.Set(320/worldScale,240/worldScale);
			var container:b2Body;
			container=world.CreateBody(bodyDef);
			polygonShape.SetAsOrientedBox(132/worldScale/2,12/worldScale/2,new b2Vec2(0/worldScale,144/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			polygonShape.SetAsOrientedBox(12/worldScale/2,200/worldScale/2,new b2Vec2(-60/worldScale,0/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			polygonShape.SetAsOrientedBox(12/worldScale/2,276/worldScale/2,new b2Vec2(60/worldScale,0/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			addEventListener(Event.ENTER_FRAME,update);
		}
		private function addCircle(pX:Number,pY:Number,h:Number):void {
			var circleShape:b2CircleShape = new b2CircleShape(h/worldScale);
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.density=3;
			fixtureDef.friction=0.4;
			fixtureDef.restitution=0;
			fixtureDef.shape=circleShape;
			var bodyDef:b2BodyDef = new b2BodyDef();
			bodyDef.type=b2Body.b2_dynamicBody;
			bodyDef.position.Set(pX/worldScale,pY/worldScale);
			bodyDef.userData=new WaterCircle();
			var box:b2Body=world.CreateBody(bodyDef);
			box.CreateFixture(fixtureDef);
		}
		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 update(e:Event):void {
			var waterParticles:Number=0;
			waterBitmapData.fillRect(waterBitmapData.rect,0xFF333333);
			world.Step(1/30,6,2);
			world.ClearForces();
			for (var b:b2Body = world.GetBodyList(); b; b = b.GetNext()) {
				if (b.GetUserData()!=null) {
					waterParticles++;
					if (b.GetPosition().y*worldScale>480) {
						world.DestroyBody(b);
					}
					else {
						waterMatrix.tx=b.GetPosition().x*worldScale;
						waterMatrix.ty=b.GetPosition().y*worldScale;
						waterBitmapData.draw(b.GetUserData(),waterMatrix);
					}
				}
			}
			if (waterParticles<300) {
				addCircle(320+1-Math.random()*2,-10,5);
			}
			world.DrawDebugData();
		}
	}
}

Now I can remove the debug draw as all Box2D assets have their own DisplayObject representing them

And now, since I am using a Bitmap, I can add a blur filter to balls

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.display.BitmapData;
	import flash.display.Bitmap;
	import flash.geom.Matrix;
	import flash.filters.BlurFilter;
	import flash.filters.BitmapFilterQuality;
	import flash.geom.Point;
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	public class Main extends Sprite {
		private var world:b2World=new b2World(new b2Vec2(0,5),true);
		private var worldScale:Number=30;
		private var waterBitmapData:BitmapData=new BitmapData(640,480,false,0xFF333333);
		private var waterBitmap:Bitmap=new Bitmap(waterBitmapData);
		private var waterMatrix:Matrix=new Matrix();
		private var waterBlur:BlurFilter=new BlurFilter(15,15,flash.filters.BitmapFilterQuality.HIGH);
		public function Main() {
			addChild(waterBitmap);
			var backgroundImage:BackgroundImage=new BackgroundImage();
			addChild(backgroundImage);
			var polygonShape:b2PolygonShape = new b2PolygonShape();
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.restitution=0;
			fixtureDef.density=1;
			fixtureDef.friction=0.4;
			var bodyDef:b2BodyDef= new b2BodyDef();
			bodyDef.position.Set(320/worldScale,240/worldScale);
			var container:b2Body;
			container=world.CreateBody(bodyDef);
			polygonShape.SetAsOrientedBox(132/worldScale/2,12/worldScale/2,new b2Vec2(0/worldScale,144/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			polygonShape.SetAsOrientedBox(12/worldScale/2,200/worldScale/2,new b2Vec2(-60/worldScale,0/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			polygonShape.SetAsOrientedBox(12/worldScale/2,276/worldScale/2,new b2Vec2(60/worldScale,0/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			addEventListener(Event.ENTER_FRAME,update);
		}
		private function addCircle(pX:Number,pY:Number,h:Number):void {
			var circleShape:b2CircleShape = new b2CircleShape(h/worldScale);
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.density=3;
			fixtureDef.friction=0.4;
			fixtureDef.restitution=0;
			fixtureDef.shape=circleShape;
			var bodyDef:b2BodyDef = new b2BodyDef();
			bodyDef.type=b2Body.b2_dynamicBody;
			bodyDef.position.Set(pX/worldScale,pY/worldScale);
			bodyDef.userData=new WaterCircle();
			var box:b2Body=world.CreateBody(bodyDef);
			box.CreateFixture(fixtureDef);
		}
		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 update(e:Event):void {
			var waterParticles:Number=0;
			waterBitmapData.fillRect(waterBitmapData.rect,0xFF333333);
			world.Step(1/30,6,2);
			world.ClearForces();
			for (var b:b2Body = world.GetBodyList(); b; b = b.GetNext()) {
				if (b.GetUserData()!=null) {
					waterParticles++;
					if (b.GetPosition().y*worldScale>480) {
						world.DestroyBody(b);
					}
					else {
						waterMatrix.tx=b.GetPosition().x*worldScale;
						waterMatrix.ty=b.GetPosition().y*worldScale;
						waterBitmapData.draw(b.GetUserData(),waterMatrix);
					}
				}
			}
			if (waterParticles<300) {
				addCircle(320+1-Math.random()*2,-10,5);
			}
			waterBitmapData.applyFilter(waterBitmapData,waterBitmapData.rect,new Point(0,0),waterBlur);
		}
	}
}

At this time I'm getting a "smoke" effect, but this is not what I want

So the final step is to add a threshold to change some colors of my bitmap balls/smoke, play a bit with transparency and add a better background

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.display.BitmapData;
	import flash.display.Bitmap;
	import flash.geom.Matrix;
	import flash.filters.BlurFilter;
	import flash.filters.BitmapFilterQuality;
	import flash.geom.Point;
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	public class Main extends Sprite {
		private var world:b2World=new b2World(new b2Vec2(0,5),true);
		private var worldScale:Number=30;
		private var waterBitmapData:BitmapData=new BitmapData(640,480,true,0x00000000);
		private var waterBitmap:Bitmap=new Bitmap(waterBitmapData);
		private var waterMatrix:Matrix=new Matrix();
		private var waterBlur:BlurFilter=new BlurFilter(15,15,flash.filters.BitmapFilterQuality.HIGH);
		public function Main() {
			var realBg:RealBg=new RealBg();
			addChild(realBg);
			addChild(waterBitmap);
			var backgroundImage:BackgroundImage=new BackgroundImage();
			addChild(backgroundImage);
			var polygonShape:b2PolygonShape = new b2PolygonShape();
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.restitution=0;
			fixtureDef.density=1;
			fixtureDef.friction=0.4;
			var bodyDef:b2BodyDef= new b2BodyDef();
			bodyDef.position.Set(320/worldScale,240/worldScale);
			var container:b2Body;
			container=world.CreateBody(bodyDef);
			polygonShape.SetAsOrientedBox(132/worldScale/2,12/worldScale/2,new b2Vec2(0/worldScale,144/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			polygonShape.SetAsOrientedBox(12/worldScale/2,200/worldScale/2,new b2Vec2(-60/worldScale,0/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			polygonShape.SetAsOrientedBox(12/worldScale/2,276/worldScale/2,new b2Vec2(60/worldScale,0/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			addEventListener(Event.ENTER_FRAME,update);
		}
		private function addCircle(pX:Number,pY:Number,h:Number):void {
			var circleShape:b2CircleShape = new b2CircleShape(h/worldScale);
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.density=3;
			fixtureDef.friction=0.4;
			fixtureDef.restitution=0;
			fixtureDef.shape=circleShape;
			var bodyDef:b2BodyDef = new b2BodyDef();
			bodyDef.type=b2Body.b2_dynamicBody;
			bodyDef.position.Set(pX/worldScale,pY/worldScale);
			bodyDef.userData=new WaterCircle();
			var box:b2Body=world.CreateBody(bodyDef);
			box.CreateFixture(fixtureDef);
		}
		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 update(e:Event):void {
			var waterParticles:Number=0;
			waterBitmapData.fillRect(waterBitmapData.rect,0x00000000);
			world.Step(1/30,6,2);
			world.ClearForces();
			for (var b:b2Body = world.GetBodyList(); b; b = b.GetNext()) {
				if (b.GetUserData()!=null) {
					waterParticles++;
					if (b.GetPosition().y*worldScale>480) {
						world.DestroyBody(b);
					}
					else {
						waterMatrix.tx=b.GetPosition().x*worldScale;
						waterMatrix.ty=b.GetPosition().y*worldScale;
						waterBitmapData.draw(b.GetUserData(),waterMatrix);
					}
				}
			}
			if (waterParticles<300) {
				addCircle(320+1-Math.random()*2,-10,5);
			}
			waterBitmapData.applyFilter(waterBitmapData,waterBitmapData.rect,new Point(0,0),waterBlur);
			waterBitmapData.threshold(waterBitmapData,waterBitmapData.rect,new Point(0,0),">",0X11444444,0x88FF00FF,0xFFFFFFFF, true);
		}
	}
}

And that's it! Not the best slime ever seen, but it's dynamically generated by Box2D, this means it has a real mass, which is quite awesome.

How would you improve it?

Download the source code of the last example.

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