我创建了这个结构:
struct MyBodyData
{
int someNumber;
};
然后创建了一个新的主体:
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);
然后尝试访问someNumber:
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);
}
}
它将someNumber显示为6-7位长的内存地址,而不是值“4”。
我错过了什么?
答案 0 :(得分:4)
body1->SetUserData(&bodyData);
您正在将正文数据设置为指针的地址 bodyData
。您不希望这样,您想将其设置为bodyData
。所以:
body1->SetUserData(bodyData);