2
votes

I have a problem with Box2d. I created an object (circle) in the center of the screen that rotates to see if I set Box2d well, following the tutorial that I found on internet. The problem is that the circle is created, but I can't rotate despite I followed exactly the tutorial found on internet. This is the code:

file .h:

b2World * _world;  
GLESDebugDraw * _debugDraw;

file .mm:

-(void)setupWorld { 

    b2Vec2 gravity = b2Vec2(0.0f, 0.0f); 
    bool doSleep = false;
    _world = new b2World(gravity, doSleep);

}

-(void)setupDebugDraw { 

    _debugDraw = new GLESDebugDraw(PTM_RATIO*[[CCDirector sharedDirector] contentScaleFactor]); 
    _world->SetDebugDraw(_debugDraw); 
    _debugDraw->SetFlags(b2DebugDraw::e_shapeBit |b2DebugDraw::e_jointBit);

}

-(void)testBox2D { 

    CGSize winSize = [CCDirector sharedDirector].winSize;

    b2BodyDef bodyDef;

    bodyDef.type = b2_dynamicBody;
    bodyDef.position = b2Vec2(winSize.width/2/PTM_RATIO,winSize.height/2/PTM_RATIO); 

    b2Body *body = _world->CreateBody(&bodyDef);

    b2CircleShape circleShape; 

    circleShape.m_radius = 25.0/PTM_RATIO;

    b2FixtureDef fixtureDef; 

    fixtureDef.shape = &circleShape; 
    fixtureDef.density = 1.0; 

    body->CreateFixture(&fixtureDef);

    body->ApplyAngularImpulse(0.01); 

}

-(void)updateBox2D:(ccTime)dt {

_world->Step(dt, 1, 1); 

[self updateBox2D:dt];

}

-(void) draw {

glDisable(GL_TEXTURE_2D); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY);

_world->DrawDebugData();

glEnable(GL_TEXTURE_2D); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY);

}


in init:

[self setupWorld]; 

[self setupDebugDraw]; 

[self testBox2D];
1

1 Answers

0
votes

Two problems:

Are you recursively calling updateBox2D? This looks like an infinite loop to me, and I'm surprised that it's not crashing your application.

Instead, you should only call your world's step once (or a few times depending on how you've setup your time step) during your CCScene tick method.

Your next problem is that you're applying a small impulse to your body, but it is only a one-time impulse... Angular impulses are still affected by damping, so the body will not rotate indefinitely by default. To keep your body rotating, you need to set the angular damping to zero:

bodyDef.angularDamping = 0.0f;