我正在编写一个游戏循环(现在),以保持稳定的25 fps。目前我正在测量~37-40。我不知道fps是否实际关闭或者它是否是测量错误。谁能告诉我什么错了?
@Override
protected void onDraw(Canvas canvas) {
mGameController.update();
mGameRenderer.render(canvas);
elapsedTime = System.currentTimeMillis() - currentTime;
currentTime = System.currentTimeMillis();
// Game loop
if (currentTime >= nextGameWorldUpdateTime) {
long millisecondsPerFrame = 40;
nextGameWorldUpdateTime = (currentTime + millisecondsPerFrame);
invalidate();
} else {
try {
long sleepTime = nextGameWorldUpdateTime - currentTime;
Thread.sleep(sleepTime);
invalidate();
} catch (InterruptedException e) {
}
}
canvas.drawText(Long.toString(fps()), mGameAssets.getScreenWidth(), mGreyPaint.getTextSize() + mGameAssets.getStatusbarHeight(), mGreyPaint);
}
private long fps() {
// Fps
fpsSamples.addLast(elapsedTime);
fpsSum += fpsSamples.getLast();
if (fpsSamples.size() > 100) {
fpsSum -= fpsSamples.getFirst();
fpsSamples.removeFirst();
}
long averageTimePerFrame = fpsSum / fpsSamples.size();
return 1000 / averageTimePerFrame;
}