Understanding custom polygons in Box2D

Last week I explained The magic of compound objects with Box2D, now it’s time to understanding custom polygons.

First, let me tell you the difference between a compound object and a custom polygon.

A compound object is an object made by two or more primitive objects (like the maze I created in this tutorial).

A custom polygon is a primitive object which is different from the standard box and circle we usually find on Box2D, such as a triangle, a pentagon or any other regular or irregular polygon you can imagine.

There is only a limit: the polygon must be convex. Box2D won’t handle collisions properly with concave polygons.

From Wikipedia: « A convex polygon is a simple polygon whose interior is a convex set.
The following properties of a simple polygon are all equivalent to convexity:
Every internal angle is less than 180 degrees or equal to 180 degrees.
Every line segment between two vertices of the polygon does not go exterior to the polygon (i.e., it remains inside or on the boundary of the polygon).

A polygon that is not convex is called concave or reentrant. A concave polygon will always have an interior angle with a measure that is strictly greater than 180 degrees.

It is possible to cut a concave polygon into a set of convex polygons. »

Ok… now we are ready to write some code…

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	import Box2D.Dynamics.Joints.*;
	import flash.events.MouseEvent;
	public class HelloWorld extends Sprite {
		var body:b2Body;
		var mouseJoint:b2MouseJoint;
		var m_world:b2World;
		var m_iterations:int=10;
		var m_timeStep:Number=1.0/30.0;
		var maze:Array = [[1,1,1,1,1,1,1,1,1],[1,0,0,0,0,0,0,0,1],[1,1,1,1,1,1,1,0,1],[1,0,0,0,1,0,0,0,1],[1,0,1,0,1,0,1,1,1],[1,0,1,0,1,0,0,0,1],[1,0,1,1,1,1,1,0,1],[1,0,0,0,0,0,0,0,1],[1,1,1,1,1,1,1,1,1]];
		public function HelloWorld() {
			addEventListener(Event.ENTER_FRAME, Update, false, 0, true);
			stage.addEventListener(MouseEvent.MOUSE_DOWN, createMouse);
			stage.addEventListener(MouseEvent.MOUSE_UP, destroyMouse);
			var worldAABB:b2AABB = new b2AABB();
			worldAABB.lowerBound.Set(-100.0, -100.0);
			worldAABB.upperBound.Set(100.0, 100.0);
			var gravity:b2Vec2=new b2Vec2(0.0,10.0);
			var doSleep:Boolean=true;
			m_world=new b2World(worldAABB,gravity,doSleep);
			// debug draw start
			var m_sprite:Sprite;
			m_sprite = new Sprite();
			addChild(m_sprite);
			var dbgDraw:b2DebugDraw = new b2DebugDraw();
			var dbgSprite:Sprite = new Sprite();
			m_sprite.addChild(dbgSprite);
			dbgDraw.m_sprite=m_sprite;
			dbgDraw.m_drawScale=30;
			dbgDraw.m_alpha = 1;
			dbgDraw.m_fillAlpha=0.7;
			dbgDraw.m_lineThickness=1;
			m_world.SetDebugDraw(dbgDraw);
			// debug draw end
			var bodyDef:b2BodyDef;
			var boxDef:b2PolygonDef;
			// lower static object
			bodyDef = new b2BodyDef();
			bodyDef.position.Set(8.5, 13);
			boxDef = new b2PolygonDef();
			boxDef.SetAsBox(8.5, 0.5);
			boxDef.friction=0.3;
			boxDef.density=0;
			body=m_world.CreateBody(bodyDef);
			body.CreateShape(boxDef);
			body.SetMassFromShapes();
			var bodyDefP:b2BodyDef = new b2BodyDef();
			var polyDef:b2PolygonDef = new b2PolygonDef();
			// a square
			polyDef.vertexCount = 4;
			polyDef.vertices[0].Set(-1,-1);
			polyDef.vertices[1].Set(1,-1);
			polyDef.vertices[2].Set(1,1);
			polyDef.vertices[3].Set(-1,1);
			polyDef.density = 1.0;
			polyDef.friction = 0.3;
			polyDef.restitution = 0.1;
			bodyDefP.position.Set(2,2);
			bodyDefP.angle = 0;
			body = m_world.CreateBody(bodyDefP);
			body.CreateShape(polyDef);
			body.SetMassFromShapes();
			// a triangle
			polyDef.vertexCount = 3;
			polyDef.vertices[0].Set(0,-1);
			polyDef.vertices[1].Set(1,1);
			polyDef.vertices[2].Set(-1,1);
			polyDef.density = 1.0;
			polyDef.friction = 0.3;
			polyDef.restitution = 0.1;
			bodyDefP.position.Set(6,2);
			bodyDefP.angle = 0;
			body = m_world.CreateBody(bodyDefP);
			body.CreateShape(polyDef);
			body.SetMassFromShapes();
			// an irregular convex polygon
			polyDef.vertexCount = 6;
			polyDef.vertices[0].Set(-1.5,-0.5);
			polyDef.vertices[1].Set(0.5,-1);
			polyDef.vertices[2].Set(1,-0.5);
			polyDef.vertices[3].Set(1,1.5);
			polyDef.vertices[4].Set(0.5,1.5);
			polyDef.vertices[5].Set(-0.5,1.3);
			polyDef.density = 1.0;
			polyDef.friction = 0.3;
			polyDef.restitution = 0.1;
			bodyDefP.position.Set(10,2);
			bodyDefP.angle = 0;
			body = m_world.CreateBody(bodyDefP);
			body.CreateShape(polyDef);
			body.SetMassFromShapes();
			// an irregular concave polygon
			polyDef.vertexCount = 6;
			polyDef.vertices[0].Set(-1.5,-0.5);
			polyDef.vertices[1].Set(0.5,-1);
			polyDef.vertices[2].Set(1,-0.5);
			polyDef.vertices[3].Set(1,1.5);
			polyDef.vertices[4].Set(0.5,1.5);
			polyDef.vertices[5].Set(1,0.5);
			polyDef.density = 1.0;
			polyDef.friction = 0.3;
			polyDef.restitution = 0.1;
			bodyDefP.position.Set(14,2);
			bodyDefP.angle = 0;
			body = m_world.CreateBody(bodyDefP);
			body.CreateShape(polyDef);
			body.SetMassFromShapes();
		}
		public function createMouse(evt:MouseEvent):void {
			var body:b2Body=GetBodyAtMouse();
			if (body) {
				var mouseJointDef:b2MouseJointDef=new b2MouseJointDef;
				mouseJointDef.body1=m_world.GetGroundBody();
				mouseJointDef.body2=body;
				mouseJointDef.target.Set(mouseX/30, mouseY/30);
				mouseJointDef.maxForce=30000;
				mouseJointDef.timeStep=m_timeStep;
				mouseJoint=m_world.CreateJoint(mouseJointDef) as b2MouseJoint;
			}
		}
		public function destroyMouse(evt:MouseEvent):void {
			if (mouseJoint) {
				m_world.DestroyJoint(mouseJoint);
				mouseJoint=null;
			}
		}
		private var mousePVec:b2Vec2 = new b2Vec2();
		public function GetBodyAtMouse(includeStatic:Boolean=false):b2Body {
			var mouseXWorldPhys = (mouseX)/30;
			var mouseYWorldPhys = (mouseY)/30;
			mousePVec.Set(mouseXWorldPhys, mouseYWorldPhys);
			var aabb:b2AABB = new b2AABB();
			aabb.lowerBound.Set(mouseXWorldPhys - 0.001, mouseYWorldPhys - 0.001);
			aabb.upperBound.Set(mouseXWorldPhys + 0.001, mouseYWorldPhys + 0.001);
			var k_maxCount:int=10;
			var shapes:Array = new Array();
			var count:int=m_world.Query(aabb,shapes,k_maxCount);
			var body:b2Body=null;
			for (var i:int = 0; i < count; ++i) {
				if (shapes[i].GetBody().IsStatic()==false||includeStatic) {
					var tShape:b2Shape=shapes[i] as b2Shape;
					var inside:Boolean=tShape.TestPoint(tShape.GetBody().GetXForm(),mousePVec);
					if (inside) {
						body=tShape.GetBody();
						break;
					}
				}
			}
			return body;
		}
		public function Update(e:Event):void {
			m_world.Step(m_timeStep, m_iterations);
			if (mouseJoint) {
				var mouseXWorldPhys=mouseX/30;
				var mouseYWorldPhys=mouseY/30;
				var p2:b2Vec2=new b2Vec2(mouseXWorldPhys,mouseYWorldPhys);
				mouseJoint.SetTarget(p2);
			}
		}
	}
}

and see what happens...

Let's look at the polygons from left to right: we have a square, a triangle, an irregular convex polygon and an irregular concave polygon.

As you can see, the concave one is not working... that's why you cannot use concave polygons.

Try to drag objects next to the concave polygon to see how much it's wrecked.

Now, let's see how to create the polygon: I am going to show you how I created the triangle.

polyDef.vertexCount = 3;
polyDef.vertices[0].Set(0,-1);
polyDef.vertices[1].Set(1,1);
polyDef.vertices[2].Set(-1,1);
polyDef.density = 1.0;
polyDef.friction = 0.3;
polyDef.restitution = 0.1;
bodyDefP.position.Set(6,2);
bodyDefP.angle = 0;
body = m_world.CreateBody(bodyDefP);
body.CreateShape(polyDef);
body.SetMassFromShapes();

Line 70: Setting the vertexCount of the polyDef variable (declared at line 54 as b2PolygonDef).

Line 71: Declaring the first vertex, at (0,-1). This is the core of the script. From the center of the yet-to-be-created polygon, I am placing the vertex one unit (a meter, in this case, refer to Understanding pixels and meters with Box2D and how to select an object with mouse - part 2 for more information) above it. The 0 represents the horizontal distance from the center (positive: to the right; negative: to the left) and the -1 represents the vertical distance (positive: to the bottom; negative: to the top).

Lines 72-73: Placing the other vertices in the same way

The remaining lines are the same for every object creation.

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

214 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
// 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