如何使用LibGDX相机与Box2D调试渲染器

7
我正在尝试使用Box2D Debug渲染器与我的LibGDX精灵和物体一起使用。问题在于渲染器将盒状物体绘制在屏幕中心,然后Sprite以其默认位置(0,0)在屏幕左下角绘制。当我移动汽车Sprite时,汽车和Debug Box同时移动,导致它们不重叠。
我知道问题出在相机上,因为我已经试着调整了几天不同的相机值。有时它们会重叠,但是Box2D Debug Body则比Car Sprite移动得更快。
有时候,Box2D body与Sprite处于相同的位置,但极小。我使用了两个相机。一个是720 x 480像素的,而Debug Camera是用米表示的,大小为24 x 16。
以下是一些可能存在问题的代码(我正在使用Stages和Actors): BattleScreen.java:
public void show() {
    battleStage = new Stage( 720, 480, false );
    // The Box2D Debug Renderer will handle rendering all physics objects for debugging
    debugRenderer = new Box2DDebugRenderer( true, true, true, true );
    debugCam = new OrthographicCamera( 24, 16 );
}
public void render() {

    // Set the Camera matrices
    battleStage.getCamera().update();       

    // Update the Physics World, use 1/45 for something around 45 Frames/Second for mobile devices
    physicsWorld.step( 1/45.0f, 8, 3 );     // 1/45 for devices 

    // Again update the Camera matrices and call the debug renderer
    //debugCam.update();
    debugRenderer.render( physicsWorld, debugCam.combined );

    // Update all Game Objects then Draw them
    battleStage.act(delta);
    battleStage.draw();
}

Car.java: (也是一个Actor)

public Car(Texture texture ) {
    super( "Car" ); 

    mSprite = new Sprite( texture );
    mSprite.setSize( 54, 105 );

    mSprite.setOrigin( mSprite.getWidth()/2, mSprite.getHeight()/2);    // set the origin to be at the center of the body

    FixtureDef carFixtureDef = new FixtureDef();
    mBody = Physics.createBoxBody( BodyType.DynamicBody, carFixtureDef, mSprite );
}

public static Body createBoxBody( final BodyType pBodyType, final FixtureDef pFixtureDef, Sprite pSprite ) {

    final BodyDef boxBodyDef = new BodyDef();
    boxBodyDef.type = pBodyType;

    // Temporary Box shape of the Body
    final PolygonShape boxPoly = new PolygonShape();
    final float halfWidth = pSprite.getWidth() * 0.5f / Consts.PIXEL_METER_RATIO;
    final float halfHeight = pSprite.getHeight() * 0.5f / Consts.PIXEL_METER_RATIO;
    boxPoly.setAsBox( halfWidth, halfHeight );  // set the anchor point to be the center of the sprite
    pFixtureDef.shape = boxPoly;

    final Body boxBody = BattleScreen.getPhysicsWorld().createBody(boxBodyDef);
    boxBody.createFixture(pFixtureDef);
    boxPoly.dispose();
    return boxBody;
}

并且让事情变得更糟的是,当我尝试让主摄像机跟随汽车时,情况变得更加复杂。

越来越接近了!我随机尝试了 debugCam.unproject( battleStage.getCamera().position ); 它几乎奏效了!现在盒子只有几个像素偏移。 - Free Lancer
2个回答

3

battleStage.getCamera().combined是什么?对我来说,Combined正常工作。


0

您需要应用以下语句来将场景与绘制的纹理组合在一起 stage.setCamera(camera);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接