问题
I'm attempting to create a "U" shape in Box2d (in Cocos2d) by joining 3 rectangles like so: |_|
It sounds like joints are not the correct solution here since I don't want any movement so I have created a main body which is the middle bit and 2 fixtures for the sides. I've added the two sides to the middle bit like this:
mainBody->CreateFixture(&leftFixtureDef);
mainBody->CreateFixture(&rightFixtureDef);
This works, however both side fixtures get added to the center of the mainBody. I can't seem to work out how to position the fixtures relative to the main body. Attaching a sprite/node to the fixture and changing the position doesn't seem to make a difference.
Any ideas?
Many thanks.
回答1:
it's the property of a shape. I did not find such property for b2CircleShape, but for b2PolygonShape
has m_centroid
paramter - it's the shape center coordinates relative to the body. Specify it to have a valid position of a shape.
For b2PolyganShape there is a method setAsBox(w, h)
but alos there is more complex one:
setAsBox(float32 width, float32 height, const b2Vec2 ¢er, float32 rotation)
Use this method or specify the centroid manualy.
Here is the code for the U shape
b2BodyDef bDef;
bDef.type = b2_dynamicBody;
bDef.position = b2Vec2(0, 0);
b2Body *body = world_->CreateBody(&bDef);
b2PolygonShape shape;
const float32 density = 10;
shape.SetAsBox(1, 0.1);
body->CreateFixture(&shape, density);
shape.SetAsBox(0.1, 1, b2Vec2(-1 + 0.1, 1), 0);
body->CreateFixture(&shape, density);
shape.SetAsBox(0.1, 1, b2Vec2(1 - 0.1, 1), 0);
body->CreateFixture(&shape, density);
来源:https://stackoverflow.com/questions/4706484/box2d-multiple-fixtures-and-positioning