Search code examples
javaswingjframejbox2d

How to display/visualize JBox2D world with Java


I wrote a JBox2D app following a FlashDevelop tutorial. Everything seems to work well from the commandline, my problem now is how to display the world in a JFrame or an alternative approach to visualize. I tried DebugDraw, but was completely lost. Thanks in advance.

public class GameWorld implements StepListener {
protected B2World b2World;
protected World world;
protected WorldView worldView;
private B2Body fallingCrate;
public static final JFrame frame = new JFrame("Platformer Game");
    ...
    ...

public GameWorld() {
    world = new World();
    worldView = new WorldView(world, (int)XAXIS, (int)YAXIS);
    setUpWorld();
    createWorldBodies();
    addCrates();
    world.addStepListener(this);
    b2World.step((float)1/30, 10);
    frame.add(worldView);
    frame.pack();
    frame.setResizable(false);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    world.start();
}

private void addCrates() {
    PolygonDef fallingBodyDef = new PolygonDef();
    fallingBodyDef.setAsBox(25f/RATIO, 25f/RATIO);
    setPhysicsProperties(fallingBodyDef, false); // set density, friction, restitution
    BodyDef crateDef = new BodyDef();
    crateDef.position.set(250f/RATIO, -30f/RATIO);
    crateDef.angle = (float) (30 * Math.PI / 180);
    fallingCrate = b2World.createBody(crateDef);
    fallingCrate.createShape(fallingBodyDef);
    fallingCrate.setMassFromShapes();
}

private void createWorldBodies() {
    PolygonDef tallBlockDef = new PolygonDef();
    tallBlockDef.setAsBox(5f/RATIO, 195f/RATIO);
    setPhysicsProperties(longBlockDef, true);
    BodyDef wallDef = new BodyDef();
    wallDef.position.set(5f/RATIO, 195f/RATIO);
    B2Body leftWall = b2World.createBody(wallDef);
    leftWall.createShape(tallBlockDef);
    leftWall.setMassFromShapes();
    ...
            ...
}

private void setUpWorld() {
    AABB universeSize = new AABB();
    universeSize.lowerBound.set(-3000f/RATIO, -3000f/RATIO);
    universeSize.upperBound.set(3000f/RATIO, 3000f/RATIO);
    Vec2 gravity = new Vec2(0f, 9.8f);
    boolean ignoreSleeping = true;
    b2World = new B2World(universeSize, gravity, ignoreSleeping);
}
    ...
    ...
    public static void main(String[] args) {
            new GameWorld();
    }

Solution

  • If you're drawing using j2d, you can grab the DebugDrawJ2D from the testbed. There's also a decent Wiki page for creating your own testbed tests if you just want to try out some physics simulations.

    If you're creating your own game or product, you'll want to get familiar with DebugDraw and using a viewport transform (so you can transform between world and view coordinates, and vice verse). JBox2D has a class to help you here as well, called OBBViewportTransform.