Luke Haas
Luke Haas

Reputation: 692

Adding a sprite to fixture in box2d

I'm trying to add a sprite texture to a box2d fixture in cocos2d. Currently I have a dynamic body (textured with a sprite) and the fixture I'm trying to add the texture to is being added to the body.

Here's my code:

b2PolygonShape fixtureShape;
fixtureShape.SetAsBox(0.6f,0.9f,b2Vec2(-1 + 0.1, 1), 45);
b2FixtureDef fixtureDef;
fixtureDef.shape = &fixtureShape;
fixtureDef.density = 0.1f;


b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
b2Body *body = world->CreateBody(&bodyDef);

b2CircleShape dynamicBox;
b2FixtureDef mainFixtureDef;
mainFixtureDef.shape = &dynamicBox; 
mainFixtureDef.density = 0.1f;

body->CreateFixture(&mainFixtureDef);
body->CreateFixture(&fixtureDef);

CCPhysicsSprite *sprite = [CCPhysicsSprite spriteWithSpriteFrameName:@"sprite1.png"];

[parent addChild:sprite];

[sprite setPTMRatio:PTM_RATIO];
[sprite setB2Body:body];

[sprite setPosition: ccp( p.x, p.y)];

I haven't been able to find any documentation on adding sprites to fixtures, does anyone know if it's possible?

Upvotes: 0

Views: 661

Answers (2)

Singhak
Singhak

Reputation: 8896

Yes you can do this by setting sprite as a user data of fixture. And setposition of sprite according to the fixture position in the world

Upvotes: 0

Andrew
Andrew

Reputation: 24846

Yes it is possible. But you have to do it yourself. Fixtures are shapes (with props) attached to the b2body. It looks pretty the same as adding children to CCNode.

So you can create a root node (just a grouping CCNode) and synchronise its position/rotation with the b2Body transformation. When adding fixtures to the body - add sprite for that fixture to the root node. And position it the same way you positioned the fixture.

Upvotes: 1

Related Questions