Hello! I’ve been wrestling with this small task I’ve been trying to overcome. I want to be able to ask the player/user what FPS he wants to limit to, and to use that. I can unlock the FPS to go as fast as it can go, or to be locked at the current UPS (Ideally, 60). The problem is, I have no idea how to do anything separate (I.E. 30, 90, 120 FPS). I’ve looked over tutorials, tricks, tips, and some other articles on this website, and am still uncertain as to how I would apply it to my current game loop.
Now, I’m not sure if this should be in the “Newbie/Debugging” or here, but regardless, here’s my current run loop (Pastebin + direct copy): http://pastebin.com/UX5HifrL
// Run Method
boolean isRunning = false;
// Variables for the FPS and UPS counter
private int ticks = 0;
private int frames = 0;
private int FPS = 0;
private int UPS = 0;
public double delta = 0;
// Used in the "run" method to limit the frame rate to the UPS
private boolean limitFrameRate = true;
private boolean shouldRender;
public synchronized void run() {
long lastTime = System.nanoTime();
double nsPerTick = 1000000000D / 60D;
long lastTimer = System.currentTimeMillis();
delta = 0D;
while (isRunning) {
long now = System.nanoTime();
delta += (now - lastTime) / nsPerTick;
lastTime = now;
// If you want to limit frame rate, shouldRender = false
shouldRender = false;
// If the time between ticks = 1, then various things (shouldRender = true, keeps FPS locked at UPS)
while (delta >= 1) {
ticks++;
tick();
delta -= 1;
shouldRender = true;
}
if (!limitFrameRate && ticks > 0)
shouldRender = true;
// If you should render, render!
if (shouldRender) {
frames++;
render();
}
// Reset stuff every second for the new "FPS" and "UPS"
if (System.currentTimeMillis() - lastTimer >= 1000) {
lastTimer += 1000;
FPS = frames;
UPS = ticks;
frames = 0;
ticks = 0;
}
}
stop();
}
I hesitate using “Thread.sleep”, mostly because I don’t want to break the functionality of my run loop as-is. I’ve been functioning on the render method being called either every tick/update, or just running all the time regardless. I guess that my question/request would be: What would be the code, or the process, to having varying FPS caps. Also, any other tips as to optimizing/using my game loop are very much appreciated. Thanks in advance!
Much obliged,
Ryan