java - Java / LibGDX 缩放问题
问题描述
我正在 libgdx 中创建一个游戏,它在 1920x1080 纵横比和 1280x720 下都可以正常工作。问题是,一些分辨率,比如 1366x768,在计算机上也很常见,不能被我的纹理大小(16px)整除,而且它不完全是 16*9,这使得一些像素变得太长或太高。这是正在发生的事情的图像。如果放大,您会看到一些像素真的很奇怪。
希望这是足够的信息,如果不是,请告诉我。
解决方案
如果所需的分辨率不适合游戏的纵横比,则需要裁剪绘图区域。
在您的渲染例程下,您应该计算正确的视口
@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();
}
推荐阅读
- python - python - 如何根据值列表按两列或多列对python pandas中的dataFrame进行排序?
- asp.net - ASP.NET - Blazor - 从模板化组件返回单击的泛型类型
- javascript - javascript: - 如何使原型/继承属性不可迭代
- javascript - 承诺如何解决?
- node.js - 列出 MongoDB 集合中的最后 N 条记录
- mysql - SQL - 涉及连接、计数和最大值的问题
- flutter - 如何生成二维码并在 Flutter 的 PDF 页面上显示
- spring - 使用 api 创建引用另一个资源的资源时,期望的正确格式是什么
- r - 如何用前一行的2列中的值递归替换元素
- sql - 如何检查多个表中是否存在列值?