视口如何在libgdx中工作,以及如何正确设置?

问题描述 投票:0回答:1

我正在学习libgdx的用法,我对视口以及对象在屏幕上的排列方式感到困惑。假设我的2D世界是2x2单位宽和高。现在,我创建一个视口为1x1的相机。所以我应该看到我的世界的25%。通常,显示器不是方形的。因此,我希望libgdx压缩并拉伸该正方形以适合显示。

对于侧面滚动条,您可以将视口高度设置为与世界高度相同,并根据宽高比调整视口宽度。与显示器的高宽比无关,您始终可以看到整个世界的高度,但在x轴上会看到不同的扩展。宽于高的显示器的人在x轴上看的可能比方形显示器的人看得更远。但是比例将保持不变,并且不会失真。到目前为止,我认为我已经掌握了视口逻辑的工作原理。

我正在与“ Learning LibGDX Game Development”一书合作,在其中您开发游戏“ canyon bunny”。可以在这里找到源代码:

Canyon Bunny - GitHub

在WorldRenderer类中,您可以找到相机的初始化:

private void init() {
        batch = new SpriteBatch();
        camera = new OrthographicCamera(Constants.VIEWPORT_WIDTH, Constants.VIEWPORT_HEIGHT);
        camera.position.set(0, 0, 0);
        camera.update();
    }

视口常量保存在单独的常量类中:

    public class Constants {
        // Visible game world is 5 meters wide
        public static final float VIEWPORT_WIDTH = 5.0f;
        // Visible game world is 5 meters tall
        public static final float VIEWPORT_HEIGHT = 5.0f;
    }

您可以看到视口是5x5。但是,当您更改窗口大小时,游戏对象在我的手机上具有正确的比例(16:9),甚至在桌面上,游戏也保持正确的比例。我不明白为什么。我希望游戏会尝试将世界的方形切口绘制到矩形显示器上,这会导致变形。为什么不是这样?为什么不需要将视口的宽度或高度调整为宽高比?

camera libgdx viewport
1个回答
0
投票

行:

cameraGUI.setToOrtho(true);

覆盖您在致电时提供的值:

cameraGUI = new OrthographicCamera(Constants.VIEWPORT_GUI_WIDTH, Constants.VIEWPORT_GUI_HEIGHT);

这是LibGDX代码,显示为什么/如何忽略您设置的视口大小:

/** Sets this camera to an orthographic projection using a viewport fitting the screen resolution, centered at
     * (Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/2), with the y-axis pointing up or down.
     * @param yDown whether y should be pointing down */
    public void setToOrtho (boolean yDown) {
        setToOrtho(yDown, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    }

    /** Sets this camera to an orthographic projection, centered at (viewportWidth/2, viewportHeight/2), with the y-axis pointing up
     * or down.
     * @param yDown whether y should be pointing down.
     * @param viewportWidth
     * @param viewportHeight */
    public void setToOrtho (boolean yDown, float viewportWidth, float viewportHeight) {
        if (yDown) {
            up.set(0, -1, 0);
            direction.set(0, 0, 1);
        } else {
            up.set(0, 1, 0);
            direction.set(0, 0, -1);
        }
        position.set(zoom * viewportWidth / 2.0f, zoom * viewportHeight / 2.0f, 0);
        this.viewportWidth = viewportWidth;
        this.viewportHeight = viewportHeight;
        update();
    }

所以您需要这样做:

cameraGUI.setToOrtho(true, Constants.VIEWPORT_GUI_WIDTH, Constants.VIEWPORT_GUI_HEIGHT);

此外,无论您在何处更改相机的位置或视口尺寸(或其他属性),都不要忘记立即致电update()

© www.soinside.com 2019 - 2024. All rights reserved.