在libgdx中渲染box2d

我有一个大小为800×480的游戏世界,使用FitViewport并且最初使用像素渲染box2d的身体+灯具,所以所有物理都显得浮动和缓慢。 看看文档,我意识到box2d使用了度量单位,所以我经历了将box2d的位置和大小转换为32倍因此我得到了一个25×15米的box2d世界。

我遇到的问题是现在box2d对象渲染得非常小。 如何缩放它们以使它们在屏幕上显示常规尺寸?

您需要在world2和box2之间使用转换因子。

在你的create()中你将拥有:

private OrthographicCamera camera; private BodyDef bodyDef; private Body body; private PolygonShape box; static float WORLD_TO_BOX, BOX_TO_WORLD, bodyWidth, bodyHieght; public Create(){ //Conversion factors WORLD_TO_BOX = 1/32f; BOX_TO_WORLD = 1/WORLD_TO_BOX; //Creation of the camera with your factor 32 camera = new OrthographicCamera(); camera.viewportHeight = Gdx.graphics.getHeight() * WORLD_TO_BOX; camera.viewportWidth = Gdx.graphics.getWidth() * WORLD_TO_BOX; camera.position.set(camera.viewportWidth/2, camera.viewportHeight/2, 0f); camera.update(); //Let's say you want to create a body in the center of your screen BodyDef = new BodyDef(); BodyDef.position.set(new Vector2(camera.viewportWidth/2, -camera.viewportHeight/2)); body = world.createBody(BodyDef); box = new PolygonShape(); //Let's say you want your body to have the shape of a square which sides size is one fifth of your camera width bodyWidth = camera.viewportWidth/10; bodyHeight = camera.viewportWidth/10; box.setAsBox(bodyWidth, bodyHeight); body.createFixture(box, 0.0f); } 

目前,您只使用转换因子WORLD_TO_BOX来创建相机。 但是如果你想在你的身体上绘制一些精灵,你将在render()中使用BOX_TO_WORLD因子。 例如,你想使用一个spritebatch在你的方块上绘制一个sprite,其精确的大小和位置在你将拥有的render()中:

 private Texture texture; public void render(){ game.batch.begin(); game.batch.setColor(1,1,1,1); //In Box2D, the orgin of a body is the center of the body, //while in your world the orgin of a sprite is the bottom left corner //I Box2D the width and the height of a body will be twice the values you entered, //while in your world the width and the height of a sprite are the exact values you entered. //Taking all this into account, to draw a sprite above a body you need to : //1 - center the sprite above the body. Ex : (body.getPosition().x - bodyWidth) for the X position //2 - draw the sprite at the right size, taking in account the factor 2. Ex : bodyWidth * 2 for the widht of the sprite //3 - Apply the BOX_TO_WORLD factor to all every sizes and distances game.batch.draw(texture, BOX_TO_WORLD * (body.getPosition().x - bodyWidth), BOX_TO_WORLD * (body.getPosition().y - bodyHeight), BOX_TO_WORLD * bodyWidth * 2, BOX_TO_WORLD * bodyHeight * 2); game.batch.end(); } 

希望它能回答你的问题。