# Using The Box2D Polygon "Set()" function?

I'm using the Box2D physics engine. And there's a type of shape for box2D called b2PolygonShape.

In this class, you can create polygons. There is also a Set() function that takes an array of points and a vertex count.

Box2D has an example like this:

// This defines a triangle in CCW order.

b2Vec2 vertices;

vertices.Set(0.0f, 0.0f);

vertices.Set(1.0f, 0.0f);

vertices.Set(0.0f, 1.0f);

int32 count = 3;

b2PolygonShape polygon;

polygon.Set(vertices, count);


This works. Yet when I tried to practice and mess with this function, I did this:

  b2Vec2 vertices;

vertices.Set(0, 0);
vertices.Set(0,10);
vertices.Set(10,10);
vertices.Set(10,0);

int32 count = 4;

b2PolygonShape polygon;

polygon.Set(vertices, count);


When I compiled and ran this, it crashed after the Set() function. Wouldn't this create a square?

Also in the console I got this:

Assertion failed: s > 0.0f


What did I do wrong?

That's because the four vertices you provided are in clockwise order and Box2D assumes they're in counter-clockwise, like in your first example. So it should work fine if you change it to:

  b2Vec2 vertices;

vertices.Set(0, 0);
vertices.Set(10,0);
vertices.Set(10,10);
vertices.Set(0,10);

int32 count = 4;

b2PolygonShape polygon;

polygon.Set(vertices, count);


And by the way, if you're just creating a box-shaped polygon, you can use the convenience function

void b2PolygonShape::SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle)

• Is there a way to make it not assume? What I'm trying to do is make a program where you can just draw shapes, sort of like PHUN. And that's where I came to these errors so I decided to try it out with the rectangle. Jul 25, 2010 at 5:15
• Not really. Polygons need to be convex and so it need to assume the winding order to verify that. If you're going to be drawing and creating polygons on the fly, you need to pre-process them to make sure they're under the vertex count limit (I think it's 6 or 8 verts) and at that point you might as well wind them correctly before you hand them off to Box2D. Jul 25, 2010 at 14:25

You could determine the winding of the polygon, and then reverse it if it is anti-clockwise.

One common method is to calculate the area of the polygon using the algorithm below. It will return a +ve number for clockwise winding, and a -ve number for anticlockwise winding.

Here is a Python example:

def poly_area(verts):
"""
Return area of a simple (ie. non-self-intersecting) polygon.
Will be negative for counterclockwise winding.
"""
accum = 0.0
for i in range(len(verts)):
j = (i + 1) % len(verts)
accum += verts[j] * verts[i] - verts[i] * verts[j]
return accum / 2