如何使用Java显示/可视化JBox2D世界

时间:2013-03-05 15:16:44

标签: java swing jframe jbox2d

我在FlashDevelop教程后写了一个JBox2D应用程序。一切似乎从命令行运行良好,我现在的问题是如何在JFrame中显示世界或者可视化的替代方法。我尝试过DebugDraw,但完全丢失了。提前谢谢。

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();
    }

1 个答案:

答案 0 :(得分:0)

如果您使用j2d绘图,则可以从测试平台抓取DebugDrawJ2D。如果您只是想尝试一些物理模拟,那么还有一个不错的Wiki页面用于创建自己的测试平台测试。

如果您正在创建自己的游戏或产品,则需要熟悉DebugDraw并使用视口转换(因此您可以在世界和视图坐标之间进行转换,反之亦然)。 JBox2D也有一个类可以帮助你,名为OBBViewportTransform