Monday, August 19, 2019

java - LibGDX: Issue with unitScale for Tiled and Box2D


I've got the following: I use a TiledMap (loaded from a .tmx), each tile 32x32 pixels in size and generate the Box2D bodies for collision from the TiledMap's ObjectLayer. That all works fine, no errors or issues. The only thing is a very strange behavior of the OrthogonalTiledMapRenderer: It gets a unitScale with the value 1 / 32 (because one unit is 32 pixels) as advised on the LibGDX GitHub wiki page. The same unit scale is used for Box2D. Thought in theory this should work just fine it renders the map very small (same is the case for the Box2D bodies, they're shown very small by the Box2DDebugRenderer):



enter image description here


Here is my code (more or less simplified):


public class MainScreen {
private OrthographicCamera camera;
private ScreenViewport viewport;
private SpriteBatch batch;
private World world;
private TiledMap tiledMap;
private OrthogonalTiledMapRenderer tiledMapRenderer;


public MainScreen() {
this.batch = new SpriteBatch();
this.world = new World(new Vector2(), true);
float unitScale = 1.0f / Constants.TILE_SIZE;

this.camera = new OrthographicCamera();
this.camera.setToOrtho(false, Gdx.graphics.getWidth() * unitScale,
Gdx.graphics.getHeight() * unitScale);
this.viewport = new ScreenViewport(this.camera);
this.tiledMap = (new TiledMapLoader()).load("level/test-level.tmx");

this.tiledMapRenderer = new OrthogonalTiledMapRenderer(this.tiledMap,
unitScale, this.batch);

// Create bodies in world based on map
Collisions.create(this.world, this.map, unitScale);
}

public void render(float delta) {
// Clear the screen
Gdx.gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

this.world.step(delta, 6, 2);
this.camera.update();
this.tiledMapRenderer.setView(this.camera);
this.tiledMapRenderer.render();
}

public void resize(int w, int h) {
this.viewport.update(w, h);

}
}

I've got no idea why this is happening... Thanks in advance :)



Answer



I just stumbled upon the answer:


I checked my ScreenViewport and seemingly the viewport somehow ignores the setToOrtho(false, width, height) and the method setUnitsPerPixel(unitScale) has to becalled first...


I never saw an example in which a viewport was used together with box2d, tilemap and unitScale, so I didn't even know about that method.


The greatest thanks to @Shiro for his help! :)


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...