How to Assign your Game data (Textures) With box2D body

When you are using Box2D in Your Game Development you might need to set graphics to box2d , so here is the step to do this.

UserData is a void pointer so you can assign your Game Data Object (eg: image object)

//set up dynamic body
b2BodyDef myBodyDef;
myBodyDef.type = b2_dynamicBody;
myBodyDef.position.Set(0, 20);
b2Body* body = world->CreateBody(&myBodyDef);

//set this Ball object in the body’s user data

body->SetUserData( this ); // here you can assign any object

//add circle fixture
b2CircleShape circleShape;
circleShape.m_p.Set(0, 0);
circleShape.m_radius = m_radius;
b2FixtureDef myFixtureDef;
myFixtureDef.shape = &circleShape;
myFixtureDef.density = 1;
Now Lets Get Back this data and draw it:

b2Body* b = m_world->GetBodyList();//get start of list
while ( b != NULL ) {

//obtain Ball pointer from user data
Ball* ball = static_cast<Ball*>( b->GetUserData() );
if ( ball != NULL ) {
ball->m_position = b->GetPosition();
ball->m_angle = b->GetAngle();
ball->m_linearVelocity = b->GetLinearVelocity();

//continue to next body
b = b->GetNext();

SOURCE; For Clear Explanation refer this Link :

Leave a Reply

Your email address will not be published. Required fields are marked *