gpt4 book ai didi

java - 在 libgdx 中渲染 box2d

转载 作者:行者123 更新时间:2023-12-01 11:47:30 25 4
gpt4 key购买 nike

我有一个使用 FitViewport 的大小为 800x480 的游戏世界,并且最初使用像素渲染 box2d 实体 + 固定装置,因此所有物理效果都显得 float 且缓慢。查看文档后,我意识到 box2d 使用度量单位,因此我将 box2d 位置和大小进行了 32 倍的转换,最终得到了 25x15 米的 box2d 世界。

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

最佳答案

您需要使用 world 和 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 来创建相机。但如果你想在你的 body 上绘制一些 Sprite ,你将在 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();
}

希望它能回答您的问题。

关于java - 在 libgdx 中渲染 box2d,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29044249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com