0
\$\begingroup\$

In my side-scroller I would like to give the illusion of the character walking forward while his sprite is actually being held in place. If he walks near the edge of the screen, I would like to adjust his position at each step so that he is remaining still while the background moves backwards at the same rate he would have been moving. I think you get what I mean.

I figured that a simple case of "position = position - velocity" would do the trick, but then I realized it is not quite that easy with box2d. Velocity is expressed not at distance per frame, but distance per second. So instead I am essentially using position = position - velocity/60 since my game refreshes (or attempts to refresh at) 60 frames per second. But I can still see some lilting in the character's movement, and if I monitor his position, it shows that it indeed changes, most likely due to variations in frame rate.

Is velocity/60 the best I can hope for, save for hard coding the stop positions?

I am using the newest release of Box2Dweb. Yes, the javascript one. Here's a sample of the code:

var posX = this.body.GetPosition().x;
var posY = this.body.GetPosition().y;
var velX = this.body.GetLinearVelocity().x;

if(posX > 21 || posX < 12){
    screen.pos -= velX;
    this.body.SetPosition(new b2Vec2(posX - (velX/60),posY));
    }

I realize I can hardcode the positions like this:

    if(posX > 21) {
        screen.pos -= velX;
        this.body.SetPosition(new b2Vec2(21,posY));
    } else if(pos < 12){
        screen.pos -= velX;
        this.body.SetPosition(new b2Vec2(12,posY));
    }

But I'm not super excited about how decidedly undynamic that option is.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

It is often advised to handle movements independent of the frame rate (since it will always vary at least a bit), as it will result in smoother transitions. So instead of hard-coding your desired value of "60", you could do the following instead:

  1. Calculate the movement you want to apply, e.g. per second.
  2. Divide that movement by the "time since the last frame" (e.g. in seconds).
  3. In the current frame, update the player's position by the result of step #2. This ensure that over one second, regardless of the frame-rate, the desired movements gets applied.

There are however valid arguments to e.g. let the physics engines run on fixed time steps (as oppose to variable time set as shown above). For more details, see this GameDev.SE thread.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .