我创建此结构:
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”。
我想念什么?
最佳答案
body1->SetUserData(&bodyData);
您正在将主体数据设置为指针
bodyData
的地址。您不想要那样,您要将其设置为bodyData
。所以:body1->SetUserData(bodyData);