PlayN Game Library Tutorial #3 – Using the Box2D library

Box2D is a free, open source library that simulated 2 dimensional physics. It works bodies made of polygons, circles or edge shapes. Bodies can be joined together with various joints and forces can act upon the bodies. It handles collisions, gravity and friction. This library is very useful when making 2D games and simulations. Originally written in C++ it has been ported to Java and other languages and can be used from PlayN.

This tutorial will be an introduction to Box2D. A Box2D simulation happens inside the org.jbox2d.dynamics.World object. This "World" has it's own coordinate system, independent of our screen/display port. The general flow is such:
  1. At start or when needed place objects, such as polygons or circles into the Box2D world.
  2. Tell Box2D do it's calculations for the next frame in the update() method.
  3. In the paint method, for every visible object.
    • get the positions of the objects from Box2D
    • translate the position and size to the view port, for example if the world was zoomed out or panned.
    • draw the objects in the calculated position.
  4. If user input is required apply it to the Box2D world.
  5. If an object needs to be removed, remove it from the Box2D world.

Leave a Reply

Your email address will not be published. Required fields are marked *