libGDX游戏开发之修改游戏帧数FPS(十三)
libGDX游戏开发之修改游戏帧数FPS(十三)
libGDX系列
,游戏开发有unity3D巴拉巴拉的,为啥还用java开发?因为我是Java程序员emm…国内用libgdx比较少,多数情况需要去官网和google找资料,相互学习的可以加我联系方式。
FPS百科:
FPS是图像领域中的定义,是指画面每秒传输帧数,通俗来讲就是指动画或视频的画面数。FPS是测量用于保存、显示动态视频的信息数量。每秒钟帧数越多,所显示的动作就会越流畅。通常,要避免动作不流畅的最低是30。
我们知道帧数越多越流畅、体验更好,但是这对CPU(核显)、GPU性能有比较高的要求。例如在游戏中FPS=60,女朋友发信息来回复时,切出游戏(窗口焦点不在游戏),这时可以降低FPS减少性能浪费。
libgdx中,通过阅读源码我们知道默认的FPS为每秒60帧,即使焦点不在窗口也是60帧。
/** Target framerate when the window is in the foreground. The CPU sleeps as needed. Use 0 to never sleep. **/
public int foregroundFPS = 60;
/** Target framerate when the window is not in the foreground. The CPU sleeps as needed. Use 0 to never sleep, -1 to not
* render. **/
public int backgroundFPS = 60;
例如设置玩游戏时60帧,切出游戏时30帧,Main代码如下:
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
// 默认帧率 60
config.foregroundFPS=60;
// 切出时帧率为30
config.backgroundFPS=30;
new LwjglApplication(new MyGdxGame(), config);
}
}
渲染代码如下:
public class MyGdxGame extends ApplicationAdapter {
SpriteBatch batch;
Texture img;
Stage stage;
Label fpsLabel;
@Override
public void create() {
batch = new SpriteBatch();
img = new Texture("badlogic.jpg");
stage = new Stage();
Label.LabelStyle style = new Label.LabelStyle(new BitmapFont(), Color.WHITE);
fpsLabel = new Label("FPS", style);
fpsLabel.setPosition(10, 450);
stage.addActor(fpsLabel);
// 手动调整CPU帧率 默认 60
Gdx.graphics.setForegroundFPS(90);
}
@Override
public void render() {
ScreenUtils.clear(1, 0, 0, 1);
batch.begin();
batch.draw(img, 0, 0);
batch.end();
fpsLabel.setText("FPS: " + Gdx.graphics.getFramesPerSecond());
stage.draw();
}
@Override
public void dispose() {
batch.dispose();
img.dispose();
}
}
效果:在游戏中,我手动调节的90不生效,就去Discord社区问了下人。
焦点不在游戏时降到30是正确的:
Discord回答:
lingkang — 今天01:57
hi
My graphics card is 1660 ti
The FPS 90 I set is invalid, still 60
How do I set high FPS?
James — 今天02:13
If your monitor is 60Hz, you must disable vsync (LWJGL2: config.vSyncEnabled = false; LWJGL3: config.useVsync(false); - might also have to change driver settings but hopefully not) to go beyond 60fps.
For LWJGL2 you also have to do config.foregroundFPS = 0 because it's by default limited to 60.
在create中修改一下,FPS修改不超过60可以不关闭。
Gdx.graphics.useVSync(false);
通过阅读源码:
也可以通过Gdx.graphics.setForegroundFPS(-1);
放飞自我:1900FPS 显卡威力!
以前经常看源码,看多脑壳疼,懒得看。遇到问题经常search白嫖,现在遇到问题还是看一圈源码算啦!