所以我正在制作一个带有怨恨的简单游戏。但我在勾选/渲染循环方面遇到了一些问题。
我需要它以每秒 30 个时钟周期运行。但 fps 需要尽可能快。
我遇到的问题是 while 循环不运行
lastTime += msPerTick;
所以我的输出看起来像这样。无需添加。没有循环。没有渲染。
x:0.375 y:0.03333333333333333
x:0.375 y:0.03333333333333333
x:0.375 y:0.03333333333333333
x:0.375 y:0.03333333333333333
x:0.375 y:0.03333333333333333
x:0.375 y:0.03333333333333333
x:0.375 y:0.03333333333333333
x:0.375 y:0.03333333333333333
这是代码片段。如果您需要更多,请告诉我。
public static final int TICKS_PER_SECOND = 30;
private static final int MAX_TICKS_PER_FRAME = 10;
private boolean running;
private Thread thread;
private int tickCount;
private int frames;
private boolean paused;
public void run() {
init();
float lastTime = (System.nanoTime() / 1000000) / 1000.0f;
running = true;
double msPerTick = 1.0 / TICKS_PER_SECOND;
while (running) {
synchronized (this) {
float now = (System.nanoTime() / 1000000) / 1000.0f;
int frameTicks = 0;
while (now - lastTime > msPerTick) {
System.out.println("x:" + (now - lastTime) + " y:" + msPerTick);
if (!paused && frameTicks++ < MAX_TICKS_PER_FRAME)
tick();
lastTime += msPerTick; //<-- Issue here
}
if (!paused) {
render((now - lastTime) / msPerTick);
}
}
//Thread.yield(); No need for yield lets use sleep.
try {
Thread.sleep(paused ? 500 : 1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
最佳答案
因为您没有添加 2 个 double 。如果您将lastTime 的类型更改为双倍,则代码将正常工作。
浮点 f = (浮点) 0.2; 双 d = 2;
f += d => 2.0 d += f => 2.2
关于java - 为什么我不能将 2 个 double 加在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28892749/