Box2DDebugRenderer and SpriteBatch misplaced

别等时光非礼了梦想. 提交于 2019-12-11 08:37:39

问题


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();

}
}

And here's how it looks thereafter

Any ideas?

Thanks!


回答1:


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.



来源:https://stackoverflow.com/questions/20604982/box2ddebugrenderer-and-spritebatch-misplaced

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!