CodeAndWeb / GBox2D

Box2D wrapper for cocos2d + box2d, works perfectly with PhysicsEditor
http://www.physicseditor.de
51 stars 18 forks source link

In GB2Sprite Position is not being updated when using CCActions. #4

Open MakarovCode opened 10 years ago

MakarovCode commented 10 years ago

Hi.

First GBox2D classes and tutorial were really useful. I don't know if there is a way for update the position of GB2Sprites, but if the answer is no, this could be a good addition to your classes.

I just add the code below inside the GB2Engine.mm inside the update method

world->Step(timeStep, velocityIterations, positionIterations);

//My Addition

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

                b2Vec2 b2Position = b2Vec2(sprite.ccPosition.x/PTM_RATIO, sprite.ccPosition.y/PTM_RATIO);
                float32 b2Angle = -1 * CC_DEGREES_TO_RADIANS(sprite.ccRotation);                
                b->SetTransform(b2Position, b2Angle);
            }
} 

This way the physic position of the object is in sync with the visual position.

But this will only works if you are using Box2D for collision detection only.

I also add this to the GB2Node.h

/**
 * Returns the object's rotation
 */
-(float)ccRotation;

/**
 * Set the object's rotation angle
 */
-(void)setCcRotation:(float)a;

And this to de GB2Node.mm


-(void)setCcRotation:(float)angle
{
    assert(body);
    ccNode.rotation = angle;
    body->SetTransform(body->GetWorldCenter(), angle);

}

-(float)ccRotation
{
    return ccNode.rotation;
}

Thanks and sorry if anything i said sounds weird but i'm not english native speaker.

Saludos