java - 循环计数不是预期的
问题描述
目前正在尝试将游戏循环管理到稳定的 60 帧。我按照我看到的例子到了一个 T,但没有得到预期的输出。开始怀疑我的电脑是不是很慢。
我使用以下代码来管理每个循环的渲染次数:
@Override
public void run() {
int fps = 60; //Number of renders wanted per second
double timePerTick = 1000000000/fps; //Alotted nanoseconds given desired fps
double delta = 0;
long now;
long lastTime = System.nanoTime();
int ticks = 0; //To track the number of times render() is called in 1 second
while(isRunning) {
now = System.nanoTime();
delta += (now - lastTime)/timePerTick; //Delta here is very small #. Represents amount of the timePerTick used after looping through one time.
timer += now - lastTime;
lastTime = now;
if(delta >= 1) {//This dictates whether a render occurs or not.
render();
ticks++;
delta = 0;
}
if(timer >= 1000000000) {//Prints out how many renders occurred in one second
System.out.println("FR at " + ticks);
ticks = 0;
timer = 0;
}
}
}
在我遵循的示例中,此代码每次打印输出一致地生成 60 帧。我的始终打印出 23、24、17、20 等。无论我如何将其更改为if(delta >= 1)
,if(delta >= .0000001)
它仍然每秒打印出大约相同数量的渲染/帧。
显然,使用较低的阈值,应该会发生更多的渲染......但这并没有发生。所以在这一点上,我非常困惑。我知道我可以使用Thread.sleep()
它,但不能保证它是准确的。
我不确定你们是否想看到我的 render() 方法,但这里是:
private void render() {
strategy = myCanvas.getBufferStrategy();
if(strategy == null) {
myCanvas.createBufferStrategy(3);
return;
}
do {
do {
g = strategy.getDrawGraphics();
g.clearRect(0, 0, 1000, 1000);
BufferedImage myImage = ImageLoader.getImage(path);//Do this in an instantiation method
g.drawImage(myImage.getSubimage(0, 0, 110, 125), x, 0, 300, 300, null);
strategy.show();
x++;
}while(strategy.contentsRestored());
g.dispose();
}while(strategy.contentsLost());
}
任何帮助是极大的赞赏!
解决方案
推荐阅读
- c# - linq to sql if control
- machine-learning - 我应该改变什么来准备我的机器学习模型以在烧瓶中创建 API 以进行 Web 部署
- oop - 在 Dart 中扩展抽象类是否会给子类另一个构造函数
- post - POST 失败(放心)嵌套数组
- mysql - 如何从查询中排除某些条目 [SQL]
- ssg - (ssg-wsg) - 在应用程序中生成令牌被 CORS 策略拒绝
- javascript - CORS:浏览器不发送或接收 Cookie
- node.js - 具有其他用户权限的 NodeJS 下载文件
- lotus-notes - 无法将文档存档到 Lotus Notes 中的存档数据库
- android - 如果所有值都为零,则 MPAndroid 酒吧聊天在中间显示零值