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