I have a main character in my Box2d game that has a b2PolygonShape
collision. When the player crouches I am changing the body to a smaller b2PolygonShape
. The logic works fine, but when I change the size (height) of the collision the character starts to fall.
Is it possible to create the new body with an offset (localPosition?) so the position of the body stays the same? This way I can play the crouch animation and change the collision without worrying that the position will change and make my sprite go bananas.
It's been a long time since I've used Box2D, but I believe I have a solution for you.
You can create another b2PoligonDef using the b2PolygonDef.SetAsOrientedBox (it allows you to set the center of the Box), and change the shapes like you're doing now on crouching and standing.
So if you were previosly using the definition of the crouching box as shapeDef.SetAsBox(1.0, 1.0), now you would change it to something like shapeDef.SetAsOrientedBox(1, 1, new b2Vec2(0, -1)).
Another option would be to declare the vertices on their own, so you would do something like:
shapeDef.vertexCount = 4;
shapeDef.vertices[0].Set(-0.5, 0);
shapeDef.vertices[1].Set( 0.5, 0);
shapeDef.vertices[2].Set( 0.5, 1);
shapeDef.vertices[3].Set(-0.5, 1);