Search code examples
javabox2dslick2d

JBox2D, use ChainShape.createChain to get a chain body, but positions of the body in JBox2D world are not correct


I want to get a physics body of 2 static wall in my game, then a ball will hit them and collide with them. The first wall is the boundary of the game window as a loop, the second wall consists of 3 parts: a stright line + an arc + again a stright line, so I use ChainShape.createChain to first get a chain shape, then add it as fixture on the body. But when I run the codes, I launch a ball to the walls, it seems like walls are not at the correct position and there is no correct collision, there is a shift even out of the game window. I don't know if there is something I did wrong, if anyone has any ideas, I'd really appreciate it!

JBox2D for physics, Slick2D for view

Game window size in pixels: 450 (width) * 900 (height)

Unit transform: 1 meter in JBox2D is 500 pixels in Slick2D

// For the first wall
BodyDef part1BodyDef = new BodyDef();
part1BodyDef.position.set(0, 0);
Body part1Body = world.createBody(part1BodyDef);
Vec2[] vecArray1 = { 
    new Vec2(0.45f, 0.9f), 
    new Vec2(0.45f, -0.9f), 
    new Vec2(-0.45f, -0.9f), 
    new Vec2(-0.45f, 0.9f) 
};
ChainShape part1Shape = new ChainShape();
part1Shape.createLoop(vecArray1, vecArray1.length);
part1Body.createFixture(part1Shape, 0);

// For the second wall
BodyDef part2BodyDef = new BodyDef();
part2BodyDef.position.set((-0.38f - 0.04f) / 2, (-0.66 + 0.78) / 2);
Body part2Body = world.createBody(part2BodyDef);
Vec2[] vecArray2 = { 
    new Vec2(-0.38f, -0.66f), 
    new Vec2(-0.38f, 0.76f), 
    new Vec2(-0.37898037f, 0.76632154f), 
    new Vec2(-0.37614113f, 0.7718118f), 
    new Vec2(-0.37181175f, 0.77614117f), 
    new Vec2(-0.36632153f, 0.77898043f), 
    new Vec2(-0.36f, 0.78f), 
    new Vec2(-0.04f, 0.5952f), 
    new Vec2(-0.04f, 0.584f) };
ChainShape part2Shape = new ChainShape();
part2Shape.createChain(vecArray2, vecArray2.length);
part2Body.createFixture(part2Shape, 0);

When I run the codes, I launch a ball to the walls, it seems like walls are not at the correct position and there is no correct collision, there is a shift even out of the game window.


Solution

  • Already solved, just because people don't need to write bodyDef.position.set(... , ...), when adding a shape on a body, the position of the body will be automatically set by the position of the shape.