Java / LibGDX缩放问题

时间:2018-11-08 15:52:51

标签: java libgdx scale resolution

我正在libgdx中创建一个游戏,并且在1920x1080宽高比和1080x720上都可以正常工作。问题是,某些分辨率(例如1366x768)在计算机上也很常见,无法通过我的纹理大小(16像素)来划分,并且它不是精确的16 * 9,这会使某些像素变得太长或太高。这是正在发生的事情的图像。如果放大,可以看到有些像素确实很奇怪。 image

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

1 个答案:

答案 0 :(得分:1)

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

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

@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)

公共矩形大小调整(浮动宽度,浮动高度){

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();
}