I create this struct:
struct MyBodyData
{
int someNumber;
};
and then created a new body:
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(0.0f, -10.0f);
b2Body* body1 = world->CreateBody(&bodyDef);
MyBodyData *bodyData = new MyBodyData();
bodyData->someNumber = 4;
body1->SetUserData(&bodyData);
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(.5f, .5f);//These are mid points for our 1m box
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
body1->CreateFixture(&fixtureDef);
And then tried to access someNumber here:
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
CCLOG(@"Hello One");
MyBodyData* data = (MyBodyData*)b->GetUserData();
if (data!=0 && data->someNumber != 0)
{
int temp;
temp = data->someNumber;
CCLOG(@"Hello Again! %d",temp);
}
}
It displays someNumber as a memory address 6-7 digits long instead of the value “4”.
What am I missing?
You’re setting the body data to be the address of the pointer
bodyData. You don’t want that, you want to set it tobodyData. So: