How to shift x position at runtime

General discussion about the R.U.B.E editor
Post Reply
kyle.bong2@gmail.com
Posts: 41
Joined: Thu May 29, 2014 5:01 am

How to shift x position at runtime

Post 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!
iforce2d
Site Admin
Posts: 861
Joined: Sat Dec 22, 2012 7:20 pm

Re: How to shift x position at runtime

Post 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() );
}
iforce2d
Site Admin
Posts: 861
Joined: Sat Dec 22, 2012 7:20 pm

Re: How to shift x position at runtime

Post 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.
kyle.bong2@gmail.com
Posts: 41
Joined: Thu May 29, 2014 5:01 am

Re: How to shift x position at runtime

Post 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!
Post Reply