首页 > 解决方案 > Java / LibGDX 缩放问题

问题描述

我正在 libgdx 中创建一个游戏,它在 1920x1080 纵横比和 1280x720 下都可以正常工作。问题是,一些分辨率,比如 1366x768,在计算机上也很常见,不能被我的纹理大小(16px)整除,而且它不完全是 16*9,这使得一些像素变得太长或太高。这是正在发生的事情的图像。如果放大,您会看到一些像素真的很奇怪。 图片

希望这是足够的信息,如果不是,请告诉我。

标签: javalibgdxscaleresolution

解决方案


如果所需的分辨率不适合游戏的纵横比,则需要裁剪绘图区域。

在您的渲染例程下,您应该计算正确的视口

@Override
public void render() {

   [...]

   // set viewport
   Gdx.gl.glViewport((int) _viewport.x, (int) _viewport.y,
            (int) _viewport.width, (int) _viewport.height);
   [...]
}

要计算正确的视口,您可以使用此函数(我基于 libgdx 为我的游戏引擎编写了此函数)

  • width:当前窗口宽度,
  • height:当前窗口高度,
  • virtualHeight/Width :游戏的原始分辨率(即 1920x1080)
public Rectangle resize(float width, float height){

    float aspectRatio = (float)width/(float)height;
    float scale = 1.0f;
    Vector2 crop = new Vector2(0f, 0f); 

    if(aspectRatio > getAspectRatio())
    {
        scale = (float)height/(float)getVirtualLandHeight();
        crop.x = (width - getVirtualLandWidth()*scale)/2f;
    }
    else if(aspectRatio < getAspectRatio())
    {
        scale = width/(float)getVirtualLandWidth();
        crop.y = (height - getVirtualLandHeight()*scale)/2f;
    }
    else
    {
        scale = (float)width/(float)getVirtualLandWidth();
    }

    float w = (float)getVirtualLandWidth()*scale;
    float h = (float)getVirtualLandHeight()*scale;

    Rectangle viewport = new Rectangle(crop.x, crop.y, w, h);

    return viewport;
}

public float getAspectRatio(){
    return getVirtualLandWidth() / getVirtualLandHeight();
}

推荐阅读