所以我理解这个概念。这个想法是 box2d 或多或少以米为单位,所以你需要从像素到它的转换。说得通。我在这里关注 box2d 的教程/介绍。它提到了进行转换,并为您提供了一些示例金额以供使用。现在,这一切都很好,但是我发现当我使用这些技术时,调试器框似乎没有呈现它们应该呈现的位置。然而,碰撞确实按预期工作。
在我的 GameScreen 类中,我是这样初始化地面的:
ground = new BodyDef();
// set the position half way up the ground
ground.position.set(0,16 * GameScreen.WORLD_TO_BOX);
groundBody = world.createBody(ground);
groundShape = new PolygonShape();
// make the height 16px so it doubles to 32
groundShape.setAsBox(Gdx.graphics.getWidth() * GameScreen.WORLD_TO_BOX, 16.0f * GameScreen.WORLD_TO_BOX);
groundBody.createFixture(groundShape, 0.0f);
我在那个屏幕上的渲染方法是这样的:
public void render(float delta) {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
camera.update();
stateTime += Gdx.graphics.getDeltaTime();
batch.begin();
batch.draw(background, 0, Gdx.graphics.getHeight() - 512, 512, 512);
batch.draw(trailingBackground, 512, Gdx.graphics.getHeight() - 512);
int heightToCover = Gdx.graphics.getHeight() - 512;
int widthToCover = Gdx.graphics.getWidth();
for(int w = 0; w < widthToCover; w += 32) {
for(int h = 0; h < heightToCover; h += 32) {
batch.draw(lightBackgroundTile, w, h, 32, 32);
}
}
player.update();
player.render(stateTime, batch);
batch.end();
levels.get(currentLevel).render(camera);
// physics updates
world.step(1/60f, 6, 2);
debugRenderer.render(world, camera.combined);
}
这是播放器类的构造函数,因此您可以看到我是如何设置它的碰撞 box2d 对象的。我还粘贴了上面渲染循环中调用的更新方法来调整精灵位置。
public Player(int x, int y, World world) {
super();
playerTexture = new Texture(Gdx.files.internal("assets/hero.png"));
init(x, y, 128, 128, playerTexture, false, world);
bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(x * GameScreen.WORLD_TO_BOX, y * GameScreen.WORLD_TO_BOX);
body = getWorld().createBody(bodyDef);
collisionBox = new PolygonShape();
collisionBox.setAsBox(32 * GameScreen.WORLD_TO_BOX, 64 * GameScreen.WORLD_TO_BOX, new Vector2(64 * GameScreen.WORLD_TO_BOX, 64 * GameScreen.WORLD_TO_BOX), 0.0f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = collisionBox;
fixtureDef.density = 10f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0f;
body.createFixture(fixtureDef);
collisionBox.dispose();
addFrame(0, 0, 128, 128);
}
public void update() {
this.setX((int) ((body.getPosition().x) * GameScreen.BOX_TO_WORLD));
this.setY((int) ((body.getPosition().y) * GameScreen.BOX_TO_WORLD));
}
现在,当我在各种计算、大小等中删除这些静态浮点数的乘法时,碰撞仍然正确并且调试器框出现。然而,将原始像素传递给 box2d 感觉不对。关于为什么调试框没有按原样显示,这里有什么我遗漏的吗?