LibGDX如何使用多个视口/相机?

时间:2016-02-28 22:04:42

标签: opengl camera libgdx rendering viewport

在我目前正在处理的LibGDX游戏中,我遇到了有关Viewports的问题。我正在尝试创建两个视口 - 一个用于保存整个屏幕,包括控件,另一个用于保存游戏的视觉效果。 This is what I mean.

然而,我遇到了使用这些视口的问题。首先,看不到平铺地图和在FitViewport的{​​{1}}内部呈现的玩家(要么没有渲染,要么没有看到可见的屏幕空间),但我看到了Rayhandler的光(和传播的比例超过1:1的比例)。 Proof

apply

我猜我完全错过了Viewport的观点。我想知道是否有任何方法可以将我的项目中的可播放区域和控制区域分开,以便例如我可以移动private OrthographicCamera camera; Viewport v1; Viewport v2; //... RayHandler devRay; //... TiledMap map; OrthogonalTiledMapRenderer tmr; Player player; @Override public void show() { camera = new OrthographicCamera(VIRTUAL_WIDTH, VIRTUAL_HEIGHT); camera.setToOrtho(false,Gdx.graphics.getWidth(),Gdx.graphics.getHeight()); //... v1 = new ScreenViewport(); v2 = new FitViewport(160, 160, camera); //... tmr = new OrthogonalTiledMapRenderer(map); tmr.setView(camera); RayHandler.useDiffuseLight(true); devRay = new RayHandler(world); } public void render(float delta) { Gdx.gl.glClearColor(1,1,1,1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); v1.apply(); //Draw Controls v2.apply(); //Draw Visuals tmr.render(); //Tiled Map Renderer player.render(); devRay.updateAndRender(); //... } 的相机,而游戏视图不会超过1:1比。谢谢你的帮助!

2 个答案:

答案 0 :(得分:2)

我遇到了同样的问题。 Official Documentation中有一个答案。

  

多个视口   如果使用屏幕大小不同的多个视口(或者使用其他设置glViewport的代码),则需要在绘制之前应用视口,以便为此视口设置glViewport。

viewport1.apply();
// draw
viewport2.apply();
// draw

使用多个阶段时:

stage1.getViewport().apply();
stage1.draw();
stage2.getViewport().apply();
stage2.draw();

答案 1 :(得分:1)

我通常做的是使用一台相机来渲染世界,并通过最后一次绘制舞台覆盖hud stage.draw()。舞台非常适合这一点。显然,这会掩盖一些游戏世界,这些游戏世界通常应该在没有hud的情况下可见,所以如果你真的想要多个“视口”,那么你必须使用Viewports

视口很容易实现,并为您处理所有事情if you pick the correct one。设置完相机后,您可以创建如下视口:

    camera = new OrthographicCamera(1920 / 2, 1080);
    //1920, 1080 for sake of example. This could be anything and it is often
    // better to not think in pixels but in world units.

    viewport = new FitViewport(camera.viewportWidth, camera.viewportHeight, camera);
    viewport.setScreenBounds(0, 0, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight());

这将使用setScreenBounds(...)在屏幕的左半部分创建一个视口。由于我们只用屏幕的一半来绘制相机上的东西,我们必须匹配宽高比,否则它会显得拉伸。

为了澄清,有时候这有点令人困惑:

float worldWidth, worldHeight; // How much of the world to display
viewport = new FitViewport(worldWidth, worldHeight, camera);

int screenPosX, screenPosY, screenWidth, screenHeight; 
// The position of the viewport where 0, 0 is bottom left and 
// Gdx.graphcis.getWidth, Gdx.graphics.getHeight is top right
viewport.setScreenBounds(screenPosX, screenPosY, screenWidth, screenHeight);

您实际上不需要指定相机的宽度和高度,因为一旦您使用连接到vp的相机点击vp.apply(),就会被覆盖。

update()方法中,在您在特定视口上绘制任何内容之前,您必须先应用视口viewport.apply()