# How to create dynamic shapes from human body into Box2D?

I’m working on a project using OpenCV and Box2d. What is the correct method to create a custom shape? I’m following Shiffman’s tutorial about polygons, the issue here is that the shape changes, it is not fixed. The first attempt is to create the triangles using Delaunay triangulation and then erase the triangles in the next cycle, but it is not stable.
The method to create the polygons is this one:

``````if (points.size() > 3) {
triangles = Triangulate.triangulate(points);
stroke(255, 100);
noFill();
beginShape(TRIANGLES);
if (steps == 0) {
for (int i = 0; i < triangles.size(); i++) {
Triangle t = (Triangle)triangles.get(i);
float x = (t.p1.x + t.p2.x + t.p3.x)/3.0;
float y = (t.p1.y + t.p2.y + t.p3.y)/3.0;
color c = get((int)x, (int)y);
if (c == -27136) {
vertex(t.p1.x, t.p1.y);
vertex(t.p2.x, t.p2.y);
vertex(t.p3.x, t.p3.y);
CustomShape cs = new CustomShape(surface);
}
surface.clear();
}
}
endShape();
}
``````

and the method to erase the polygons then is this one:

``````if (steps == 1) {
for (int i = 0; i < polygons.size(); i++) {
CustomShape cp = polygons.get(i);
cp.killBody();
}
polygons.clear();
}
steps ++;
steps = steps % 2;
``````

And in the Box2D object I use this method to create the polygon:

``````  void makeBody(ArrayList<Vec2> surface_in) {
// println(surface_in);
// Define a polygon (this is what we use for a rectangle)
PolygonShape sd = new PolygonShape();

// from the ArrayList we made
Vec2[] vertices = new Vec2[3];
// for (int i = 0; i < vertices.length; i++) {
//   vertices[i] = box2d.vectorPixelsToWorld(surface_in.get(i));
// }
vertices[0] = box2d.vectorPixelsToWorld(surface_in.get(0));
vertices[1] = box2d.vectorPixelsToWorld(surface_in.get(1));
vertices[2] = box2d.vectorPixelsToWorld(surface_in.get(2));

// Create the polygon!
sd.set(vertices, vertices.length);

// Define the body and make it from the shape
BodyDef bd = new BodyDef();
bd.type = BodyType.STATIC;
bd.position.set(box2d.coordPixelsToWorld(center));
body = box2d.createBody(bd);
body.createFixture(sd, 0.0);
}
``````

What is the correct way to play with custom shapes in Box2D? My approach is not the best at all.

2 Likes