Search code examples
ioscocos2d-iphonebox2dphysics-engine

Update CCSprite postion when b2Body moves?


In my Box2d game I found out that I must update my CCSprite position in the game loop so it works properly. I have looked through the Box2D docs to see what APIs there are to get the b2Body coordinates but I didn't see anything and this seems unclear. Should I be moving each CCSprite manually or is there an easy way to move all CCSprite on screen to the b2Bodys associated with them?

Does anyone have any idea on how to do this?

Thanks!

Edit1: Would this code just update every sprite in my world to the b2Body corresponding to them? And this will work with the x and y axis and rotation correct?

for(b2Body *b = _world->GetBodyList(); b; b=b->GetNext()) {
        if (b->GetUserData() != NULL) {
            CCSprite *sprite = (CCSprite *)b->GetUserData();

            b2Vec2 b2Position = b2Vec2(sprite.position.x/PTM_RATIO,
                                       sprite.position.y/PTM_RATIO);
            float32 b2Angle = -1 * CC_DEGREES_TO_RADIANS(sprite.rotation);

            b->SetTransform(b2Position, b2Angle);
        }
    }

Solution

  • simply do this:

    In your init class schedule the tick method like this

    [self schedule: @selector(tick:)];

    -(void)tick: (ccTime) dt
    
    
     for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
     {
         if (b->GetUserData() != NULL)
         {
             CCSprite *spr= (CCSprite*)b->GetUserData();
             CCSprite *myActor = (CCSprite*)b->GetUserData();
             myActor.position = CGPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);
             myActor.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
         }
    

    }