Libgdx单个舞台中的背景和前景

3

我的要求:

  1. 背景填充整个物理屏幕(必要时进行拉伸)
  2. 保持前景资产的纵横比(使用虚拟宽度和高度)

为此,我在屏幕中使用了两个阶段,如下面的代码所示。

public void render(float delta) {
    backgroundStage.act(delta);
    backgroundStage.draw();
    foregroundStage.act(delta);
    foregroundStage.draw();
    }

public void resize(int width, int height) {
    background.setWidth(width);
    background.setHeight(height);
    backgroundStage.setViewport(width, height, true);
    foregroundStage.setViewport(MainGame.WIDTH, MainGame.HEIGHT, true);
    foregroundStage.getCamera().position.set(-foregroundStage.getGutterWidth(),-foregroundStage.getGutterHeight(),0);
    }

在我所阅读的所有教程中,我只看到每个屏幕只使用了一个舞台。那么,如何在单个舞台中满足这两个要求呢?拥有单独的舞台会太昂贵吗?(我已经了解到SpriteBatch对象很重!)
这是我解决问题的方法:
为了摆脱背景舞台,我更新了我的渲染和调整窗口大小的函数。基本上,我将背景的右下角移动到了(-gutterWidth,-gutterHeight),并将纹理区域的宽度和高度值加倍,再加上两个边距值。现在舞台被排除了 :-)
public void render(float delta) {
    Gdx.gl.glClearColor(0, 1, 0, 0.5f);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    foregroundStage.getSpriteBatch().begin();
    foregroundStage.getSpriteBatch().draw(backgroundImage,-gw,-gh,backgroundImage.getRegionWidth()+2*gw,backgroundImage.getRegionHeight()+2*gh);
    foregroundStage.getSpriteBatch().end();
    foregroundStage.act(delta);
    foregroundStage.draw();


public void resize(int width, int height) {
    screenW = width;
    screenH = height;
    foregroundStage.setViewport(MainGame.WIDTH, MainGame.HEIGHT, true);
    gw = foregroundStage.getGutterWidth();
    gh = foregroundStage.getGutterHeight();
    foregroundStage.getCamera().translate(-gw,-gh,0);
    }
1个回答

1

您可以使用两个阶段,但对于您的情况,最好通过在单个阶段内创建两个组来解决此问题:

Stage stage = new Stage();

Group background = new Group();
background.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Group foreground = new Group();
foreground.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

// Notice the order
stage.addActor(background);
stage.addActor(foreground);

foreground.addActor(new Actor());
// Or anything else you want to add like you normally would to the stage. 

background.addActor(new Image()); // your background image here.

Gdx.input.setInputProcessor(stage);

谢谢。但是我想要不同的视口用于背景和前景,就像我在上面的代码中写的那样。我如何在不自己计算前景大小的情况下实现这一点? - coolscitist
你可以将视口设置为前景视口,然后调整背景图像的边界大小以匹配所需的大小。甚至可以将图像作为纹理区域单独从舞台渲染,这样可以按照所需的喜欢进行渲染。有几种选择,但没有理由使用两个舞台来完成。除非您计划在背景中渲染大量内容(除了您的背景图像),那么使用两个舞台可能更合理。 - Jyro117
是的,我做到了。我将背景移动到(-gutterWidth,-gutterHeight),并将两倍的gutter宽度和高度添加到纹理区域的区域宽度和高度中。现在舞台已经消失了 :-) - coolscitist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接