简体   繁体   中英

LibGDX Box2D not rendering

I am new to Box2D and LibGDX and I am trying to render a simple test. The code should render a 2x2 box, but it doesn't Here is my code:

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

I can't seem to display anything, all I get is a black screen. Does anyone know what's wrong?

Thanks!

I had the same problem. You mentioned the solution in the comments section but i wanted to give an official answer to this.

in your code (and mine) there was no camera.viewportWidth and camera.viewportHeight set... just set these two values either explicitly via camera.viewportWidth = Gdx.graphics.getWidth() or by passing the values in through the constructor like so:

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

(for those who don't know i am using the Gdx method of getting the screen resolution because box2d is usually used in Java with libGDX, you may substitute Gdx.graphics.getWidth() with whatever screen resolution you are using)

Set your camera position like this

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

and add this

camera.update();

i'have the same problem i've solved it to call for all super()

super.pause();

super.resize(width, height);

super.render();

super.dispose();

super.resume();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM