The below code helps you to rotate a body in Box2D manually.
-(void) start { rot_sprite = [CCSprite spriteWithFile:[NSString stringWithFormat:@"rot_sprite.png" ]]; [self addChild: rot_sprite]; b2BodyDef bodyDef; b2Vec2 initVel; b2PolygonShape shape; b2CircleShape circleShape; b2FixtureDef fd; b2Body * rotating_body; b2RevoluteJointDef revJointDef; b2DistanceJointDef jointDef; b2Vec2 pos; bodyDef.position.Set(11.043825f, 4.984064f); bodyDef.angle = 0.000000f; bodyDef.userData = rot_sprite; rotating_body = world->CreateBody(&bodyDef;); initVel.Set(0.000000f, 0.000000f); rotating_body->SetLinearVelocity(initVel); rotating_body->SetAngularVelocity(0.000000f); b2Vec2 rotating_body_vertices[4]; rotating_body_vertices[0].Set(-0.143426f, -1.565737f); rotating_body_vertices[1].Set(0.143426f, -1.565737f); rotating_body_vertices[2].Set(0.143426f, 1.565737f); rotating_body_vertices[3].Set(-0.143426f, 1.565737f); shape.Set(rotating_body_vertices, 4); fd.shape = &shape; fd.density = 0.015000f; fd.friction = 0.300000f; fd.restitution = 0.600000f; fd.filter.groupIndex = int16(0); fd.filter.categoryBits = uint16(65535); fd.filter.maskBits = uint16(65535); rotating_body->CreateFixture(&fd;); //calling the schedular at intervals to rotate the body. [self schedule: @selector(rotateBody) interval:0.01]; } -(void)rotateBody { angle += 0.02; b2Vec2 pos = rotating_body.GetPosition(); rotating_body.SetTransform(pos, angle); }
Here the body is named “rotating_body” which is going to rotate and a sprite named “rot_sprite” is it’s userData, please give your own image for it.
Make sure that you have it in your resources otherwise your program will crash.
Note: call this function in a schedular for the body, here-rotating_body to rotate.
Adjust the angle and the schedular-interval for better results.