java 游戏开发:如何限制 FPS?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3102888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:22:36  来源:igfitidea点击:

Game Development: How to limit FPS?

javac++algorithmframe-rate

提问by Martijn Courteaux

I'm writing a game, and I saw the FPS algorithm doesn't work correctly (when he have to calculate more, he sleeps longer...) So, the question is very simple: how to calculate the sleeptime for having correct FPS?

我正在写一个游戏,我看到 FPS 算法不能正常工作(当他必须计算更多时,他睡得更久......)所以,问题很简单:如何计算拥有正确 FPS 的睡眠时间?

I know how long it took to update the game one frame in microseconds and of course the FPS I want to reach.

我知道以微秒为单位更新一帧游戏需要多长时间,当然还有我想要达到的 FPS。

I'm searching crazy for a simple example, but I can't find one....

我正在疯狂地寻找一个简单的例子,但我找不到一个......

The code may be in Java, C++ or pseudo....

代码可能是 Java、C++ 或伪代码......

回答by aioobe

The time you should spend on rendering one frame is 1/FPSseconds (if you're aiming for, say 10 FPS, you should spend 1/10 = 0.1 seconds on each frame). So if it took Xseconds to render, you should "sleep" for 1/FPS - Xseconds.

你应该花在渲染一帧上的时间是1/FPS秒(如果你的目标是 10 FPS,你应该在每一帧上花 1/10 = 0.1 秒)。因此,如果X渲染需要几秒钟,您应该“休眠”1/FPS - X几秒钟。

Translating that to for instance milliseconds, you get

将其转换为例如毫秒,您会得到

ms_to_sleep = 1000 / FPS - elapsed_ms;

If it, for some reason took more than 1/FPSto render the frame, you'll get a negative sleep time in which case you obviously just skip the sleeping.

如果它,出于某种原因花费的时间超过1/FPS渲染帧,您将获得负的睡眠时间,在这种情况下,您显然只是跳过睡眠。

回答by JSB????

The number of microseconds per frame is 1000000 / frames_per_second. If you know that you've spent elapsed_microsecondscalculating, then the time that you need to sleep is:

每帧的微秒数是1000000 / frames_per_second. 如果你知道你已经花在elapsed_microseconds计算上,那么你需要睡觉的时间是:

(1000000 / frames_per_second) - elapsed_microseconds

回答by Lance

Try...

尝试...

static const int NUM_FPS_SAMPLES = 64;
float fpsSamples[NUM_FPS_SAMPLES]
int currentSample = 0;

float CalcFPS(int dt)
{
    fpsSamples[currentSample % NUM_FPS_SAMPLES] = 1.0f / dt;
    float fps = 0;
    for (int i = 0; i < NUM_FPS_SAMPLES; i++)
        fps += fpsSamples[i];
    fps /= NUM_FPS_SAMPLES;
    return fps;
}

... as per http://www.gamedev.net/community/forums/topic.asp?topic_id=510019

...根据http://www.gamedev.net/community/forums/topic.asp?topic_id=510019

回答by virious

Take a look at thisarticle about different FPS handling methods.

看看这个文章关于不同的FPS处理方法。