LibGDX Box2D无法渲染

时间:2012-07-16 15:51:32

标签: java libgdx box2d

我是Box2D和LibGDX的新手,我正在尝试渲染一个简单的测试。代码应该呈现一个2x2的框,但它不是这里是我的代码:

public class PhysicsDemo implements ApplicationListener {
World world = new World(new Vector2(0, -20), true);
Box2DDebugRenderer debugRenderer;
private OrthographicCamera camera;


@Override
public void create() {      

    camera = new OrthographicCamera();
    camera.position.set(0, 0, 0);


    //Ground body
    BodyDef groundBodyDef =new BodyDef();
    groundBodyDef.position.set(0.0f, -20f);
    Body groundBody = world.createBody(groundBodyDef);
    PolygonShape groundBox = new PolygonShape();
    groundBox.setAsBox(50.0f, 10.0f);
    groundBody.createFixture(groundBox, 0.0f);

    //Dynamic Body
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyType.DynamicBody;
    bodyDef.position.set(0.0f, 4.0f);
    Body body = world.createBody(bodyDef);
    PolygonShape dynamicBox = new PolygonShape();
    dynamicBox.setAsBox(1.0f, 1.0f);
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = dynamicBox;
    fixtureDef.density = 1.0f;
    fixtureDef.friction = 0.3f;
    body.createFixture(fixtureDef);

    debugRenderer = new Box2DDebugRenderer();


}





@Override
public void dispose() {



}

@Override
public void render() {      

    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    debugRenderer.render(world, camera.combined);


}

@Override
public void resize(int width, int height) {
}

@Override
public void pause() {
}

@Override
public void resume() {
}
}

我似乎无法显示任何内容,我得到的只是一个黑屏。有谁知道什么是错的?

谢谢!

3 个答案:

答案 0 :(得分:2)

我遇到了同样的问题。您在评论部分提到了解决方案,但我想对此给出正式答案。

在您的代码(和我的代码)中没有设置camera.viewportWidthcamera.viewportHeight ...只需通过camera.viewportWidth = Gdx.graphics.getWidth()明确设置这两个值 或者通过构造函数传递值,如下所示:

OrthographicCamera camera = new OrthographicCamera(Gdx.graphics.getWidth(), 
                                                   Gdx.graphics.getHeight());

(对于那些不知道我正在使用Gdx获取屏幕分辨率的方法因为box2d通常在Java中使用libGDX,你可以用Gdx.graphics.getWidth()替换你正在使用的任何屏幕分辨率)

答案 1 :(得分:1)

像这样设置相机位置

  

camera.position.set(camera.viewportWidth * .5f,camera.viewportHeight * .5f,0f);

并添加此

  

camera.update();

答案 2 :(得分:0)

我有同样的问题我已经解决了所有超级()

的问题

super.pause();

super.resize(宽度,高度);

super.render();

super.dispose();

super.resume();