今天写游戏必需计算FPS,就在网上搜到了Loon的一个java 游戏计算FPS的类,修正了一下如下(版权属原作者):
package com.px.FPS;import java.text.DecimalFormat;public class CFPSMaker{ public static final int FPS = 8; public static final long PERIOD = (long) (1.0 / FPS * 1000000000); public static long FPS_MAX_INTERVAL = 1000000000L; private double nowFPS = 0.0; private long interval = 0L; private long time; private long frameCount = 0; private DecimalFormat df = new DecimalFormat("0.0"); public void makeFPS() { frameCount++; interval += PERIOD; //当切实间隔相称工夫时。 if (interval >= FPS_MAX_INTERVAL) { //nanoTime()归来最准确的可用系统计时器的目前值,以毫微秒为单位 long timeNow = System.nanoTime(); // 获得到现在为止的工夫距离 long realTime = timeNow - time; // 单位: ns //换算为切实的fps数值 nowFPS = ((double) frameCount / realTime) * FPS_MAX_INTERVAL; //改变数值 frameCount = 0L; interval = 0L; time = timeNow; } } public long getFrameCount() { return frameCount; } public void setFrameCount(long frameCount) { this.frameCount = frameCount; } public long getInterval() { return interval; } public void setInterval(long interval) { this.interval = interval; } public double getNowFPS() { return nowFPS; } public void setNowFPS(double nowFPS) { this.nowFPS = nowFPS; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } public String getFPS() { return df.format(nowFPS); }}
容易的利用措施:
率先,初始化一个FPSMaker实例
CFPSMaker fpsMaker;fpsMaker = new CFPSMaker();
然后,在必需计算FPS时初始化以下目前工夫:
fpsMaker.setNowFPS(System.nanoTime());
最后,在游戏循环中计算和揭示目前游戏帧速:
fpsMaker.makeFPS();GameManager.drawFPS(fpsMaker.getFPS() + " FPS");
OVER!我们会补益匪浅的正规的代码审查(codeinspection)是长进代码功德的最壮大的技巧之一,