【发布时间】: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