0
votes

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?

2
No. Fixtures are used by the physics engine only. Sprites hook onto Body's in box2d. This explains a bit: stackoverflow.com/a/5862128/2700842 - Nick Terry
@NickTerry: Sprites are not related to the bodies. The are two different engines. Box2d - for physics, Cocos2d - for graphics. It is fully up to you how you draw the physics. You are not limited to hooking sprites onto Body - Andrew

2 Answers

1
votes

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.

0
votes

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