changing box2d body shapes dynamically
Asked Answered
C

1

11

Is it possible to change the shape of a Box2d b2Body dynamically? I want to do this to achieve the following.

i). Increasing the radius of a circle shape at a certain rate

ii). Changing the dimensions of a bounding box for a sprite to match the changing animation frames.

Concord answered 12/6, 2013 at 13:3 Comment(4)
You can't change the shape of box2d b2body dynamically, but you can achieve that by destroying and recreating the b2body.Shrewmouse
you only need to recreate the fixture, not the whole bodyPresswork
Yes my mistak, i was about to say but wrote b2body. You just have to recreate fixture only.Shrewmouse
@LearnCocos2D: +1 for an example on this.Concord
S
5
   float radius;
   radius = 1;

Create body:

b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(300/PTM_RATIO, 150/PTM_RATIO);
body = world->CreateBody(&bodyDef);

b2CircleShape circleShape;
circleShape.m_radius = radius;

b2FixtureDef fixtureDef;
fixtureDef.shape = &circleShape;
fixtureDef.density = 1;
fixtureDef.friction = 0.3f;
body ->CreateFixture(&fixtureDef);

In your touch method:

  - (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
   {  

    if (body != NULL) {

    b2Fixture *fixtureA = body->GetFixtureList();
    body->DestroyFixture(fixtureA);

    b2CircleShape circleShape;
    circleShape.m_radius = radius + 0.3; 

    b2FixtureDef fixtureDef;
    fixtureDef.shape = &circleShape;
    fixtureDef.density = 1;
    fixtureDef.friction = 0.3f;
    body->CreateFixture(&fixtureDef);

    radius = radius + 0.3;

   }

With every touch body will become bigger for 0.3.

Syncytium answered 5/7, 2014 at 10:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.