From PNG to Box2D – first attempt

If you followed the posts using marching squares algorithm to trace the contour of an image and reduce the number of points in a polygon with the Ramer-Douglas-Peucker algorithm you probably imagined where I wanted to go… I am going to use Antoan Angelov’s b2Separator class to convert any PNG image to a Box2D body, assuming the PNG has transparency.

Look at the example:

On the left, the original image with the contour traced by marching squares, on the right, the same contour optimized with Ramer-Douglas-Peucker algorithm, and on the bottom the static Box2D body made with b2Separator class using 1/10 of the total vertices to save fixtures.

It’s just an attempt and can be fairly optimized, but it starts to work pretty well.

This is the code, which is just a mix of the codes you can find in the Ramer-Douglas-Peucker algorithm and b2Separator class examples.

How would you optimize the process? Download the source code.

  • Wow, really impressive!

  • Zo

    Very cool. Although the Ramer-Douglas-Peucker algorithm seems work much better with complex shapes. It seems to fail with simple shapes (like a basic rectangles and triangles)

    • Davide Ingrosso

      Yes, because it is supposed to simplify complex shapes: a triangle and a rectangle are already optimal shapes, you can’t reduce them anymore [: