从帧率代码中得到奇怪的结果
我试图将游戏保持在 60 fps,但我从代码中得到奇怪的结果,例如“2-8000 fps”,为什么这不保持在 60?
public static void main(String[] args) {
joglplat m = new joglplat();
while(true){
long startTime = System.nanoTime() / 1000000;
try
{
// 123456: 6 zeros => 16ms
long nsToSleep = 16000000 - (System.nanoTime() - lastFrame);
System.out.println("ns: " + nsToSleep);
lastFrame = System.nanoTime();
if(nsToSleep > 0)
{
System.out.println("ns2: " + (nsToSleep/1000));
System.out.println("ns3: " + (nsToSleep%1000));
Thread.sleep(nsToSleep/16000000, (int)(nsToSleep % 1000));
}
else
{
Thread.yield(); // Only necessary if you want to guarantee that
// the thread yields the CPU between every frame
}
}
catch(Exception e){
e.printStackTrace();
}
m.controls();
m.update();
m.repaint();
System.out.println("framerate: " + (System.nanoTime() / 1000000 - startTime));
}
}
I'm trying to keep my game at 60fps, but I'm getting strange results from my code like "2-8000 fps" Why isn't this staying at 60?
public static void main(String[] args) {
joglplat m = new joglplat();
while(true){
long startTime = System.nanoTime() / 1000000;
try
{
// 123456: 6 zeros => 16ms
long nsToSleep = 16000000 - (System.nanoTime() - lastFrame);
System.out.println("ns: " + nsToSleep);
lastFrame = System.nanoTime();
if(nsToSleep > 0)
{
System.out.println("ns2: " + (nsToSleep/1000));
System.out.println("ns3: " + (nsToSleep%1000));
Thread.sleep(nsToSleep/16000000, (int)(nsToSleep % 1000));
}
else
{
Thread.yield(); // Only necessary if you want to guarantee that
// the thread yields the CPU between every frame
}
}
catch(Exception e){
e.printStackTrace();
}
m.controls();
m.update();
m.repaint();
System.out.println("framerate: " + (System.nanoTime() / 1000000 - startTime));
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的输出是程序运行的秒数,而不是帧速率。 您应该将帧数(您没有收集的帧数)除以总运行时间。
要获取帧计数,只需在游戏循环之外添加一个新变量,并每次通过...递增它......
但是请注意,这将为您提供程序整个执行过程中的平均帧速率。 另外两个选项是获取瞬时帧速率和过去 N 帧的平均帧速率。
所有样式合而为一(未经测试/未编译,因此可能会有一些错误,但应该让您朝着正确的方向开始):
Your output is the number of seconds your program has run for, not framerate. You should be dividing your frame count (which you aren't collecting) by the total time run.
To get the frame count, simply add a new variable outside of your game loop, and increment it each time through...
Note, however, that this will give you the average framerate throughout the entire execution of your program. Two other options you have are to get the instantaneous framerate, and the average framerate over the past N frames.
All styles in one (untested/uncompiled, so might have some errors, but should get you started in the right direction):
我怀疑这是由 Thread.sleep() 不准确引起的:
有什么理由必须像这样降低帧速率吗? 也许您可以更全面地解释您想要实现的目标?
My suspicion is that this is caused by the inaccuracy of Thread.sleep():
Is there any reason why you have to hold the framerate down like this? Perhaps you can explain more fully what you are trying to accomplish?