需要在使用LibGDX和tiled map的游戏中实现视差效果。背景应该以不同的速度移动,而前景则保持不变。在文档https://github.com/libgdx/libgdx/wiki/Tile-maps中提到:
通过分别渲染每个图层并为每个图层修改视图,您还可以实现视差效果。
当前实现:使用PlayScreenVariantOne
一切正常,但是背景与前景以相同的速度移动。
public class PlayScreenVariantOne implements Screen {
private TextureAtlas atlas;
private OrthographicCamera gameCam;
private Viewport viewport;
private TmxMapLoader mapLoader;
private TiledMap map;
private OrthogonalTiledMapRenderer renderer;
...
// ...
// ... bla-bla-bla...
// ...
@Override
public void render(float delta) {
update(delta);
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderer.setView(gameCam);
renderer.render();
game.batch.setProjectionMatrix(gameCam.combined);
game.batch.begin();
player.draw(game.batch);
game.batch.end();
hud.stage.draw();
}
}
视差实现: 使用PlayScreenVariantTwo
将前景和背景以相同速度呈现。视差效果无法工作! :*(
public class PlayScreenVariantTwo implements Screen {
private TextureAtlas atlas;
private OrthographicCamera gameCam;
private Viewport viewport;
private TmxMapLoader mapLoader;
private TiledMap map;
private OrthogonalTiledMapRenderer renderer;
...
// ...
// ... bla-bla-bla...
// ...
@Override
public void render(float delta) {
update(delta);
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
int[] backgroundLayers = { 7 };
int[] ground = { 9 };
renderer.setView(gameCam.combined, (gameCam.position.x - gameCam.viewportWidth / 2 - 2), gameCam.position.y - gameCam.viewportHeight / 2, gameCam.viewportWidth, gameCam.viewportHeight);
renderer.render(backgroundLayers);
renderer.setView(gameCam.combined, (gameCam.position.x - gameCam.viewportWidth / 2) / 10, gameCam.position.y - gameCam.viewportHeight / 2, gameCam.viewportWidth * 10, gameCam.viewportHeight);
renderer.render(ground);
game.batch.setProjectionMatrix(gameCam.combined);
game.batch.begin();
player.draw(game.batch);
game.batch.end();
hud.stage.draw();
}
}