【问题标题】:LibGDX Box2D not renderingLibGDX Box2D 不渲染
【发布时间】:2015-02-08 00:07:18
【问题描述】:

我是 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() {
}
}

我似乎无法显示任何内容,我得到的只是黑屏。有谁知道怎么回事?

谢谢!

【问题讨论】:

  • 您没有设置相机位置。也许一切正常,但相机位置不正确。
  • 谢谢!我想我为新的 OrthographicCamera 使用了错误的构造函数。我现在使用的那个要求视口尺寸。我现在工作。

标签: java libgdx box2d


【解决方案1】:

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

在您的代码(和我的)中没有 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() 替换为您使用的任何屏幕分辨率)

【讨论】:

    【解决方案2】:

    这样设置你的相机位置

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

    并添加这个

    camera.update();

    【讨论】:

      【解决方案3】:

      我有同样的问题,我已经解决了它调用所有 super()

      super.pause();

      super.resize(width, height);

      super.render();

      super.dispose();

      super.resume();

      【讨论】:

        猜你喜欢
        • 2023-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-23
        • 1970-01-01
        • 1970-01-01
        • 2016-06-22
        • 2015-07-04
        相关资源
        最近更新 更多