Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

cocos2d iphone - Box2d multiple fixtures and positioning

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 &center, 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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...