简体   繁体   中英

libGDX orthographic camera view size (with Box2D)

I have next easy class with one ball and four walls around screen:

SpriteBatch batch;
Box2DDebugRenderer debugRenderer;
World world;
OrthographicCamera camera;

public float VIRTUAL_WIDTH  = 720f;
public float VIRTUAL_HEIGHT = 1280f;

@Override
public void create () {

    batch = new SpriteBatch();

    camera = new OrthographicCamera(VIRTUAL_WIDTH, VIRTUAL_HEIGHT);
    world = new World(new Vector2(0, -9), true);

    debugRenderer = new Box2DDebugRenderer();

    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.DynamicBody;

    CircleShape circleShape = new CircleShape();
    circleShape.setRadius(50);

    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = circleShape;
    fixtureDef.restitution = 1;

    Body body = world.createBody(bodyDef);
    body.createFixture(fixtureDef);

    createWall(0f, -VIRTUAL_HEIGHT/2, VIRTUAL_WIDTH/2, 30f);
    createWall(0f, VIRTUAL_HEIGHT/2, VIRTUAL_WIDTH/2, 30f);
    createWall(-VIRTUAL_WIDTH/2, 0f, 30f, VIRTUAL_HEIGHT/2);
    createWall(VIRTUAL_WIDTH/2, 0f, 30f, VIRTUAL_HEIGHT/2);

}

private void createWall(float x, float y, float hx, float hy){

    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.StaticBody;
    bodyDef.position.set(x, y);

    PolygonShape polygonShape = new PolygonShape();
    polygonShape.setAsBox(hx, hy);

    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = polygonShape;

    world.createBody(bodyDef).createFixture(fixtureDef);

}

@Override
public void render () {

    camera.update();

    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    world.step(1 / 60.0f, 8, 3);
    batch.setProjectionMatrix(camera.combined);

    batch.begin();
    debugRenderer.render(world, camera.combined);
    batch.end();

}

And it's do next screen on my device (maybe not perfect screenshot):

在此输入图像描述

The screen is slightly shifted to the left, it's because rounding errors?

UPDATE:

在此输入图像描述

Instead of this

public float VIRTUAL_WIDTH  = 720f;
public float VIRTUAL_HEIGHT = 1280f;

Try this

public float VIRTUAL_WIDTH  = Gdx.graphics.getWidth();
public float VIRTUAL_HEIGHT =  Gdx.graphics.getHeight();

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