I'm using a tiled tmx map, and I created a class that adds bodies to each tile within a certain layer. This has been working great so far except for when a character or an enemy moves around on the screen, its body gets stuck on an edge between two tiles.
This seems to happen "sometimes" and in certain spots. Jumping makes you unstuck but it's annoying when it happens, and I tried increasing the position iterations, but the problem keeps reoccurring.
Here's what my game looks like:
Answer
I ended up redoing to algorithm for building the map. This seems to be working really really well
I wrote this to build it, this basically makes a body for each tile, if there are tiles next to each other, horizontally, it will group them together and create a single body for those tiles
private static void buildCollision(Map map, World world){
TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get("collisionlayer");
BodyDef bDef = new BodyDef();
PolygonShape shape = new PolygonShape();
FixtureDef fDef = new FixtureDef();
fDef.density = 2.5f;
fDef.isSensor = false;
fDef.friction = 0;
fDef.restitution = 0;
bDef.type = BodyType.StaticBody;
Body tileBody = world.createBody(bDef);
tileBody.setUserData("ground");
int cellcounter = 0;
TiledMapTileLayer.Cell cell, nextCell, prevCell;
int firstCellIndexX = 0, firstCellIndexY = 0;
for(int j = 0; j < layer.getHeight(); j++){
for(int i = 0; i < layer.getWidth(); i++){
cell = layer.getCell(i, j);
prevCell = layer.getCell(i-1, j);
nextCell = layer.getCell(i+1, j);
if(cell != null){
cellcounter++;
if(prevCell == null){
firstCellIndexX = i;
firstCellIndexY = j;
}
if(nextCell == null){
float width = layer.getTileWidth() * cellcounter * scaledRatio;
float height = layer.getTileHeight() * scaledRatio;
shape.setAsBox(width/2, height/2, new Vector2((firstCellIndexX * layer.getTileWidth() * scaledRatio) + (width/2), (firstCellIndexY * layer.getTileHeight() * scaledRatio) + (height/2)), 0);
fDef.shape = shape;
tileBody.createFixture(fDef);
cellcounter = 0;
}
}
}
}
shape.dispose();
}
No comments:
Post a Comment