Tuesday, July 23, 2019

libgdx - Box2d bodies that are really close together, are getting “stuck”


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:


enter image description here



Answer



I ended up redoing to algorithm for building the map. This seems to be working really really well



enter image description here


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

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