Page 1 of 1

How to shift x position at runtime

Posted: Sun Nov 02, 2014 2:26 am
by kyle.bong2@gmail.com
Hi all,

What's the best way to shift x position on all items generated by rube? I want to dynamically shift everything to the left by X position in my game. Would it be best to shift the position in json or in the world?

Best!

Re: How to shift x position at runtime

Posted: Mon Nov 03, 2014 1:47 pm
by iforce2d
RUBE cannot help with things that happen "at runtime". There is a function in b2World called ShiftOrigin, which I recommended to you in another thread here a couple of days ago. If you really don't want to use that function for some reason, you could move all bodies yourself like this (eg. to move everything 100 units to the right):

Code: Select all

for (b2Body* b = world->GetBodyList(); b; b = b->GetNext()) {
    b2Vec2 newPos = b->GetPosition() + b2Vec2( 100, 0 );
    b->SetTransform( newPos, b->GetAngle() );
}

Re: How to shift x position at runtime

Posted: Mon Nov 03, 2014 1:54 pm
by iforce2d
Hmm... maybe you are talking about shifting only a subset of bodies from one json? For example, if you are loading in pre-fabricated pieces of a side-scrolling level, then you might want to move some parts of it after loading. If that is the case, you could use the getAllBodies of b2dJson to get a list of all bodies in the json that was just loaded:

Code: Select all

json.readFromFile( "enemy.json", errorMsg, world );

vector<b2Body*> allBodies;
json.getAllBodies( allBodies ); // all bodies in enemy.json

b2Vec2 offset( x, y );
for (int i = 0; i < allBodies.size(); i++) {
    b2Body* b = allBodies[i];
    b->SetTransform( b->GetPosition() + offset, b->GetAngle() );
}
Notice that the readFromFile function is given a third parameter "world", which would be the existing world to load into.

Re: How to shift x position at runtime

Posted: Mon Nov 03, 2014 10:43 pm
by kyle.bong2@gmail.com
Correct that's exactly what I want to do, load pre-fabricated pieces of a side-scrolling level. I ended up with the same solution. Thanks very much for validating it!