So I am making a simple game with spites. But im having some issues with the tick/render loop.
I need it to run at 30 ticks a second. But the fps needs to be as fast as it can.
The issue I am having is the while loop doesn't run
lastTime += msPerTick;
So my output looks like this. No adding. No loop. No render.
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
Here is a snippet of the code. Let me know if you need more.
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();
}
}
}
Because you're not adding 2 doubles. If you change the type of lastTime to double the code will work fine.
float f = (float) 0.2; double d = 2;
f += d => 2.0 d += f => 2.2