代码之家  ›  专栏  ›  技术社区  ›  Nano

LibGDX-定心正交相机

  •  0
  • Nano  · 技术社区  · 9 年前

    所以我正在做一个游戏,我想让游戏中的相机在所有设备长度的屏幕中间居中。我希望 this picture 可以更好地解释我想要实现的目标。我试过设置相机的位置,但这对我没有效果。

        scrnHeight = Gdx.graphics.getHeight();
        if (scrnHeight <= HEIGHT) {
    
            cam.setToOrtho(false, 480, 800);
        } else {
            cam.setToOrtho(false, 480, scrnHeight);
        }
    
        //This is the part that seems to be giving me all the issues
        cam.position.set(cam.viewportWidth/2,cam.viewportHeight/2, 0);
        cam.update();
    
        Gdx.input.setInputProcessor(this);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    
        gsm.update(Gdx.graphics.getDeltaTime());
        gsm.render(batch);
    
        batch.begin();
        batch.draw(border, -(border.getWidth() - WIDTH) / 2, -(border.getHeight() / 4));
        batch.end();
    

    我不知道我在设置位置时是否给了它错误的坐标,或者发生了什么导致了垂直居中不足。任何帮助都将不胜感激。

    1 回复  |  直到 9 年前
        1
  •  1
  •   julian    9 年前

    LibGDX中的正交相机位置表示位置 游戏中 ,而不是在设备屏幕上,因此更改它不会实际移动设备上的游戏屏幕。

    因此,您可以使用相机位置在游戏中移动和定位相机。
    例如,响应于玩家输入移动:

    if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
        cam.translate(-3, 0, 0); // Moves the camera to the left.
    }
    if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
        cam.translate(3, 0, 0);  // Moves the camera to the right.
    }
    

    如你所见,我们在游戏中根据玩家的输入左右移动相机。

    但是,您的代码还有一些问题,如未设置批投影矩阵:

    batch.setProjectionMatrix(cam.combined);
    

    并在每一帧将相机位置重置为视口的中心:

    // Don't run this each frame, it resets the camera position!
    cam.position.set(cam.viewportWidth/2,cam.viewportHeight/2, 0);
    cam.update(); // <- However, you must run this line each frame.
    


    最后,将LibGDX应用程序集中在设备屏幕上应该在LibGDX之外完成,否则,如果你打算为同一个LibGDX app使用备用屏幕,那么你应该创建另一个摄像头来全屏工作,并在实际的游戏摄像头(通常用于HUD等)之前渲染它。。。