这个游戏循环中的FPS下降是多少?

时间:2014-06-27 00:19:30

标签: java class rendering

有人可以告诉我为什么FPS每隔几次迭代就会从100(期望)下降到91吗?我在原始应用程序中尽可能简洁,我使用了双缓冲和主动渲染,在这个例子中同样的事情发生但我使用被动渲染。 FPS不断下降到100到91,我无法弄明白为什么!

代码

import javax.swing.JPanel;
import javax.swing.JFrame;


import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;

public class Test extends JPanel implements Runnable {

    Image img;

    int fps;
    @Override 
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if(img != null) {
            g.drawImage(img, 0, 0, null);
        }

    }

    public void gameUpdate() {

}

public void gameRender() {
Graphics g  = getGraphics();
g.setColor(Color.BLACK);
for(int i = 0; i < 1000; i++)
    g.fillRect(0, 0, 50, 50);

}


    public void startGame()  {
        if(thread == null) {
            thread = new Thread(this);
            thread.start();
        }
    }

    private Thread thread;
    @Override
    public void run() {
    long beforeTime = 0;
    long afterTime = 0;
    long timeDiff = 0;
    int period = 10000000;
    long sleepTime = 0; 
    long overSleepTime = 0;
        while(true) {
            beforeTime = System.nanoTime();
            gameUpdate();
            gameRender();
            repaint();
            afterTime = System.nanoTime();
            timeDiff = afterTime - beforeTime;
            sleepTime = (period - timeDiff) - overSleepTime;

            if(sleepTime > 0) {
            try {
                Thread.sleep(sleepTime/1000000L);
            }  catch (InterruptedException e){}
            long threadSleepTime = System.nanoTime() - afterTime;
            overSleepTime  = threadSleepTime - sleepTime;

            fps = (int)FPSCounter.getFPS(threadSleepTime, timeDiff);
            System.out.println(fps);
        } // end if

        } 

    }

    public void addNotify() {
        super.addNotify();
        startGame();
    }



    public static void main(String[] args) {
        JFrame f = new JFrame("Title");
        f.setSize(500, 500);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setContentPane(new Test());
        f.setVisible(true);

    }


}

单独的课程

/**
 * Return the current FPS
 * @param threadSleep Amount of time thread has slept
 * @param renderTime Amount of time took rendering/updating
 * @return
 */
public static double getFPS(long threadSleep, long renderTime) {
    return 1000000000 / (threadSleep + renderTime);
}

0 个答案:

没有答案