libGDX Tiled Box2D - main

25th March 2021, 17:00:00

Intro

Ever wanted to create a tile map and automatically convert objects or collider objects into box2d bodies but couldn’t figure out how to? Welp, here we go!

Repo

https://github.com/lyze237-examples/LibgdxTiledBox2DExample

General setup

I recommend to always use viewports for your project, and let it handle everything. Manually working with a camera can result in strange behaviors. For more infos on how to use them, look at the official wiki.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public class Main extends ApplicationAdapter
{
private TiledMap map;
private OrthogonalTiledMapRenderer mapRenderer;

private World world;
private Box2DDebugRenderer worldRenderer;
private int tileSize;

private Viewport viewport;

@Override
public void create()
{
world = new World(new Vector2(0, -10), true);
worldRenderer = new Box2DDebugRenderer();

map = new TmxMapLoader().load("Map.tmx");
tileSize = ((TiledMapTileLayer) map.getLayers().get(0)).getTileWidth();
mapRenderer = new OrthogonalTiledMapRenderer(map, 1f);

// This ensures that 30x20 tiles are always going to be visible, doesn't matter what the windows resolution is.
viewport = new ExtendViewport(30 * tileSize, 20 * tileSize);

parseMap();
}

private void parseMap()
{
// TODO ...
}

@Override
public void render()
{
Gdx.gl.glClearColor(0.1f, 0.1f, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

world.step(Gdx.graphics.getDeltaTime(), 6, 2);

viewport.apply();

mapRenderer.setView((OrthographicCamera) viewport.getCamera());
mapRenderer.render();

worldRenderer.render(world, viewport.getCamera().combined);
}

@Override
public void resize(int width, int height)
{
viewport.update(width, height, true);
}
}

Additionally let’s define a little helper method, so we don’t need to copy paste so much code.:

1
2
3
4
5
6
7
8
private BodyDef getBodyDef(float x, float y)
{
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.StaticBody;
bodyDef.position.set(x, y);

return bodyDef;
}

Object layer vs tile objects

There are two options available for you to pick, one has more manual labor, the other creates some problems.

Basically you can decide to draw objects in an object layer yourself for collisions, or define collisions in each tile once, and parse those.

The downside to the first option is that you need to do that all yourself, however you can therefore precisely define all collisions, and this also means that you don’t have a ton of bodies and bugs on corners.

Map setup

Let’s create a basic map to get started

Screenshot of a simple map

Helpful tip

I’d recommend to change snapping to “pixel”, so that drawing objects will always be pixel aligned.

Snapping