Java-Gaming.org Java4K winners: [ by our judges | by the community ]         
Featured games (67)
games approved by the League of Dukes
Games in Showcase (∞)
games submitted by our members



News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  Print  
  Capped framerate and "getting" FPS  (Read 780 times)
0 Members and 1 Guest are viewing this topic.
Offline Shazer2

Jr. Member
**

Posts: 66
Medals: 3



« on: 2012-01-21 07:48:58 »

I'm trying to learn how to cap my framerate to 60 using JUST Java. I have a simple understanding yet far from perfect or even knowing how to get it working. I just know I need to get the time --> do rendering updates etc --> get the time again. I then need to do something with the difference (lastTime - firstTime) but I'm not sure what.

Any help with game looping and getting/setting the FPS would be much appreciated.

~Shazer2

"When you want to be successful as bad as you want to breathe, then you will be successful." - Eric Thomas
Offline theagentd

JGO Wizard
****

Posts: 1392
Medals: 88



« Reply #1 on: 2012-01-21 10:52:05 »

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
long frameNanoseconds = 1000*1000*1000 / DESIRED_FPS;

long startTime = System.nanoTime();

while(gameIsRunning){

    updateAndRenderEverything();

    long timeTaken = System.nanoTime() - startTime;
    if(timeTaken < frameNanoseconds){
        int sleepMillis = (frameNanoseconds - timeTaken) / (1000*1000);
        try{
            Thread.sleep(sleepMillis);
        catch(InterruptedException ex){
            ex.printStackTrace();
        }
    }

    startTime += frameNanoseconds;

}

There is no god.
Online ra4king

JGO Kernel
*****

Posts: 3151
Medals: 196


I'm the King!


« Reply #2 on: 2012-01-21 17:25:22 »

For Thread.sleep(...) to work reliably on windows, use the following trick:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
new Thread() {
    {
        setDaemon(true);
        start();
    }
   
    public void run() {
        while(true) {
            try{
                Thread.sleep(Long.MAX_VALUE);
            }
            catch(Exception exc) {}
        }
    }
};

Pages: [1]
  Print  
 
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.16 | SMF © 2011, Simple Machines Valid XHTML 1.0! Valid CSS!
Page created in 0.104 seconds with 20 queries.