【问题标题】:How to use LibGDX cameras with Box2D Debug Renderers如何将 LibGDX 相机与 Box2D 调试渲染器一起使用
【发布时间】:2012-04-01 19:08:07
【问题描述】:

我正在尝试将 Box2D 调试渲染器与我的 LibGDX 精灵和身体一起使用。我遇到的问题是渲染器在屏幕的中心绘制 Box Body,然后 Sprite 在屏幕左下角的默认位置(0,0)绘制。当我移动汽车精灵时,汽车和调试框都会移动,使它们不重叠。

我知道问题出在相机上,因为这几天我一直在搞乱不同的相机值。有时它们会重叠,但 Box2D Debug Body 的移动速度比 Car Sprite 快。

有时 Box2D 的主体与 Sprite 处于同一位置,但非常小。我正在使用 2 个摄像头。一个是 720 x 480。调试相机以米为单位,因此它是 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 );,它几乎成功了!该框现在只偏离了几个像素。

标签: java android graphics box2d libgdx


【解决方案1】:

battleStage.getCamera().combined 呢?组合对我来说效果很好。

【讨论】:

    【解决方案2】:

    您必须应用以下语句将主体与绘制的纹理结合起来 stage.setCamera(相机);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多