Friday, September 25, 2015

libgdx - How can I convert a tilemap to a Box2D world?


I want to use Box2D physics and lighting with a .tmx map. How can I "convert" a tilemap to Box2D world? My basic idea is to go through the tiles on the map and create an object for them in Box2D.


I'm using the Tiled map editor for the tilemap, and the target platform is PC.


Firstly, is this a good solution for my idea? Or is this even possible?
Secondly, if yes, then I dont know how to get the tile's position.



My code so far:


public class WorldLoader {
public static TiledMap map;

public static void loadMap(String mapName) {
map = new TmxMapLoader().load(mapName);
TiledMapTileLayer collisionLayer = (TiledMapTileLayer) map.getLayers().get("collision");

for (int x = 0; x < collisionLayer.getWidth(); x++) {
for (int y = 0; y < collisionLayer.getHeight(); y++) {

Cell cell = collisionLayer.getCell(x, y);

if (cell != null && cell.getTile() != null) {
// float tileX = collisionLayer.getProperties().containsKey("x");
// float tileY = cell.getTile().getProperties().get("y", Integer.class);

BodyDef bodyDef = new BodyDef();
bodyDef.position.set(tileX, tileY);

PolygonShape shape = new PolygonShape();

shape.setAsBox(16, 16);

Body body = GameWorld.world.createBody(bodyDef);
body.createFixture(shape, 0f);

shape.dispose();
}
}
}


}

}




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...