Search code examples
javalibgdxbox2d

How to get the distance that a body has moved during a box2D world step?


I'm trying to implement linear interpolation and a fixed time step for my game loop. I'm using the libGDX engine and box2D. I'm attempting to find the amount the simulation moves my character's body during a world step like this:

  old_pos = guyBody.getPosition();
  world.step(STEP_TIME, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
  new_pos = guyBody.getPosition();
  printLog(new_pos.x-old_pos.x);

This returns 0 each time. The simulation works fine, and the body definitely moves each step.

Additional code:

@Override
public void render(float delta) {

    accumulator+=delta;
    while (accumulator>=STEP_TIME){
        accumulator-=STEP_TIME;
        stepWorld();
    }
    alpha = accumulator/STEP_TIME;
    update(delta);
    //RENDER 
}


    private void stepWorld() {
       old_pos = guyBody.getPosition();
       old_angle = guyBody.getAngle() * MathUtils.radiansToDegrees;
       world.step(STEP_TIME, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
       new_angle = guyBody.getAngle() * MathUtils.radiansToDegrees;
       new_pos = guyBody.getPosition();
    }

I'm attempting to use alpha to check how far I am in between physics steps so I can interpolate a Sprite's position.

Thanks!


Solution

  • Body's getPosition method is returning Vector reference - that means that you not copying it by value but only assign "pointer" on position object to old_pos/new_pos. However you are assigning it once before step and then after step all in all both variables keeps the same object with state after step already.

    What you need to do is to copy position vector by value - to do this you can use Vector's cpy() method.

    Your code should looks like

    old_pos = guyBody.getPosition().cpy();
    world.step(STEP_TIME, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
    new_pos = guyBody.getPosition().cpy();
    printLog(new_pos.x-old_pos.x);
    

    If you do not use y coordinate you should also consider keeping only x in float type variable to not copy whole object (however it should not really impact your performance).