Juan Chô
Juan Chô

Reputation: 572

Box2DDebugRenderer and SpriteBatch misplaced

I am playing with libgdx for making yet another physics game :) and I have found something weird. Namely I use SpriteBatch for rendering images at the same time with Box2DDebugRenderer for debuging.

But when the physics acts, they appear to be misplaced. I wrote:

public class Canon implements ApplicationListener {
    private OrthographicCamera camera;
private Box2DDebugRenderer debugRenderer;

    /...
public void create() {              
    camera = new OrthographicCamera(CAMERA_WIDTH, CAMERA_HEIGHT);
    world = new World(new Vector2(0f, -9.8f), true);
        camera.position.set(CAMERA_WIDTH/2, CAMERA_HEIGHT/2, 0f); 
        camera.update();        
    debugRenderer = new Box2DDebugRenderer();
    spriteBatch = new SpriteBatch();
        //Create a canon. A rectangle :)
        bd = new BodyDef();
    fd = new FixtureDef(); fd.density = 1;
    PolygonShape ps = new PolygonShape();

    // Cannon
    bd.type = BodyDef.BodyType.StaticBody;
    bd.position.set(new Vector2(8, 5));
    ps.setAsBox(5f, 1f);
    cannonBody = world.createBody(bd);
    fd.shape = ps;
    cannonBody.createFixture(fd);
    }

@Override
public void render() {      
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    debugRenderer.render(world, camera.combined);
    world.step(BOX_STEP, BOX_VELOCITY_ITERATIONS, BOX_POSITION_ITERATIONS);  
        spriteBatch.begin();
        Sprite s = (Sprite)targetBody1.getUserData();
        spriteBatch.draw(s.getTexture(), 
            (targetBody1.getPosition().x - bodyWidth/2)*ppuX,            (targetBody1.getPosition().y - bodyheight/2)*ppuY,
            0f, 0f, bodyWidth*ppuX, bodyheight*ppuY, 1f, 1f, radToGrad*targetBody1.getAngle(), 0, 0, s.getTexture().getWidth(), s.getTexture().getHeight(), false, false);
    spriteBatch.end();

}
}

enter image description here

And here's how it looks thereafterenter image description here

Any ideas?

Thanks!

Upvotes: 1

Views: 531

Answers (1)

Juan Chô
Juan Chô

Reputation: 572

I found it. This is due to the fact rotations in OpenGL are done around the bottom left corner, whereas rotations in Box2D are done around mass center's body. Rotating the texture around mass center body gives right physics/texture behavior.

Upvotes: 1

Related Questions