What is the correct way to reposition a sprite with a physics body attached?

In Box2d, its quite straightforward - you just call the setTransform to reposition a physics object.

But when using a PhysicsBody attached to a Sprite, I am not sure how to reposition them correctly. Setting the position of the sprite does not change the position of the physics body, and PhysicsBody does not have a setPosition() method.

What am I missing ?

There are physics examples in cpp-tests

I looked at cpp-tests for physics already. It is still unclear - There are examples on using actions, but couldn’t find one which directly sets the position of an already existing physics object attached to sprite.

The closes is setPositionOffset, but its a bit unclear to me.

I only use setPosition In my most heavily utilized physics game but I don’t reposition the physics body a lot. It stays pretty constant with the sprite the whole time it is utilized.

Ok, thanks! I found that it takes some time for physics objects connected via joints to also be repositioned, so wasn’t sure if that was the correct way. I guess I have to reposition those manually as well to avoid lag.

Oh I do position everything manually as a matter of habit.

If it Cocos2dx yesh just do a sprite->setPostion(0,0);
if it’s Box2d then you need to use the tranform function of box2d. The sprite’s are moved normly to the center of box2d physics witch is 0,0 = center of box2d object and not Cocos 0,0 witch is top left
cocos2dx defult anchor point. (0.5,0.5) center.
Box2d has bodys’ so somting like this.

box2dBody* body;
body->SetTransform(b2Vec2( postion.x , postion.y ), body->GetAngle());

//My Box2d Updade is like this. It move’s the sprite to the center of the box2d body and rotates it…
void PhysicsClass::UpdateWorld(void)
world->Step(UPDATE_INTERVAL, velocityIterations, positionIterations);

for (b2Body *b = world->GetBodyList(); b; b=b->GetNext()) {
    UserData *Object = (UserData *)b->GetUserData();
    if (Object) {
        if( Object->sprite ){
            Object->sprite->setPosition(Vec2(b->GetPosition().x * PTM_RATIO ,b->GetPosition().y * PTM_RATIO));
            Object->sprite->setRotation(-1 * CC_RADIANS_TO_DEGREES( b->GetAngle() ));


So once I attach the physics body to Sprite, I should just setPosition of the sprite ?

Correct, but as I discovered sometimes setPosition seems to be ignored. I solved it by using an action instead, see Help Please: Sprite::SetPosition() does not seem to work in onContact callbacks for Chipmunk physics engine - cocos2d-x / C++ - Cocos Forums

1 Like