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 | public class Main extends ApplicationAdapter |
Additionally let’s define a little helper method, so we don’t need to copy paste so much code.:
1 | private BodyDef getBodyDef(float x, float y) |
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
Helpful tip
I’d recommend to change snapping to “pixel”, so that drawing objects will always be pixel aligned.
Links
- If you want to work with an object layer, click here.
- If you want to work with tileset collisions, click here instead.