简体   繁体   中英

accessing box2d userdata

I know that this might sound pretty simple. I am having a problem with accessing the userdata of a b2Body in one method through the update method. I need to access the userdata property in the update method to set multiple gravities. I am just not getting it. Below is the update method

-(void) update: (ccTime) dt
{
int32 velocityIterations = 8;
int32 positionIterations = 1;
world->Step(dt, velocityIterations, positionIterations);    

for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
    if (b->GetUserData() != NULL) {
        if (b == spriteData) {
            b->ApplyForce( b2Vec2(0.0,9.8*b->GetMass()),b->GetWorldCenter()); // here 0.0 is x, 9.8 is y (the gravity)
        }
    }
}

}

How do I access the userdata property (spriteData) which is in another method. Please Help

I suggest you declare an data structure MyUserData (use whatever name you see fit). It will contains two things :

  1. pointer to the actual user data object
  2. id number

Use this structure to store you body's user data and use the id to recognize specific user data :

 if (b->GetUserData() != NULL) {
        MyUserData *myUserData = (MyUserData *)b->GetUserData();
        if (myUserData->id == <id for sprites which require other gravity force>) {
            b->ApplyForce( b2Vec2(0.0,9.8*b->GetMass()),b->GetWorldCenter()); // here 0.0 is x, 9.8 is y (the gravity)
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM