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…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 | 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.
70 71 72 73 74 75 76 77 78 79 80 81 | 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.
They can be easily customized to meet the unique requirements of your project.















(8 votes, average: 4.38 out of 5)









This post has 12 comments
Andy Cook
Nice work. Box2D is really powerful and useful, and I am glad you are learning it. I am probably going to teach this in my Flash class next semester and these tutorials are good starting points. Thanks!
anlik
up,up,up. I come here everyday for Box2D.Thanks
Alex clark
Yes but I keep getting an error on line 134 when I export, why is this?
jeanpier
Nice, next game i’ll be using Box2D for sure.
Thanks Emanuele!
Alex clark
Please help, with all the code I download and copy/paste (test) I get error 1046, I’m obviously not doing something? can you put me in the right direction?
thanks
Alex
vitaLee
great series of tutorials on the box2d subject.
i find them very helpful and interesting.
thanks.
box2dfriend
is possible auto get edge points array when you get a bitmapdata? ha ,if it can be ,great!
KyallB
One really important thing I’ve found: you MUST set the points in a clockwise direction, or Box2D will think the shape is inside-out, with some really bizarre results.
fabio
why is there an error on line 134 when exporting from the example? Can anyone help??
Thanks!
Aaron
Hello,
I’m just picking up the new version of box2d, and I can’t seem to find any information about custom shapes in the new rewritten engine. Would you be so kind as to point me in the right direction?
Thanks for your time & cheers!
Aaron
joe
It dosn’t work…It pokes through the bottom and you can’t drag it with your mouse :( sorry, It was a nice idea but yeah! Anyways, thanks for trying! I love the stuff on your website!
Processing meets Box2D and blob detection | der hess
[...] normal vectors does not point inside the object (check chapter 4.4 Polygon Shapes). Even using a polygon object would make more sense instead of using the surface [...]