【发布时间】:2010-12-27 08:22:13
【问题描述】:
我正在寻找一种在游戏应用程序中计算每秒帧数的方法,问题是我没有这些应用程序的源代码,它们内部没有实现这样的功能。老实说,我真的不希望这是可能的,但值得一问。
为了完全清楚,我知道我需要主绘画循环的基本知识和代码来计算 FPS。
最好的问候
【问题讨论】:
我正在寻找一种在游戏应用程序中计算每秒帧数的方法,问题是我没有这些应用程序的源代码,它们内部没有实现这样的功能。老实说,我真的不希望这是可能的,但值得一问。
为了完全清楚,我知道我需要主绘画循环的基本知识和代码来计算 FPS。
最好的问候
【问题讨论】:
当你有一个主绘制循环时,计算 FPS 有什么问题(不是吗?)。
我不熟悉 Android 功能,但我确信它在任何操作系统上的任何游戏中都是一样的。制作游戏的最简单方法是制作 2 个线程。第一个将用于逻辑操作(计算轨迹、对象位置随时间的变化等)。第二个线程将获取当前游戏状态(由第一个线程计算)并将其绘制在屏幕上。
这是两个线程上的注释代码带有 FPS 计数器:
//Class that contain current game state
class GameState {
private Point objectPosition;
public Point getObjectPosition() {
return objectPosition;
}
public void setObjectPosition(Point pos) {
this.objectPosition = pos;
}
}
//Runnable for thread that will calculate changes in game state
class GameLogics implements Runnable {
private GameState gameState; //State of the game
public GameLogics(GameState gameState) {
this.gameState = gameState;
}
public void run() {
//Main thread loop
while (true) { //Some exit check code should be here
synchronize (gameState) {
gameState.setObjectPosition(gameState.getObjectPosition()+1); //Move object by 1 unit
}
Thread.sleep(1000); //Wait 1 second until next movement
}
}
}
//Runnable for thread that will draw the game state on the screen
class GamePainter implements Runnable {
private Canvas canvas; //Some kind of canvas to draw object on
private GameState gameState; //State of the game
public GamePainter(Canvas canvas, GameState gameState) {
this.canvas = canvas;
this.gameState = gameState;
}
public void drawStateOnCanvas() {
//Some code that is rendering the gameState on canvas
canvas.drawLine(...);
canvas.drawOtherLine(...);
....
}
public void run() {
//Last time we updated our FPS
long lastFpsTime = 0;
//How many frames were in last FPS update
int frameCounter = 0;
//Main thread loop
//Main thread loop
while (true) { //Some exit check code should be here
synchronize (gameState) {
//Draw the state on the canvas
drawStateOnCanvas();
}
//Increment frame counter
frameCounter++;
int delay = (int)(System.getCurrentTimeMillis() - lastFpsTime);
//If last FPS was calculated more than 1 second ago
if (delay > 1000) {
//Calculate FPS
double FPS = (((double)frameCounter)/delay)*1000; //delay is in milliseconds, that's why *1000
frameCounter = 0; //Reset frame counter
lastFpsTime = System.getCurrentTimeMillis(); //Reset fps timer
log.debug("FPS: "+FPS);
}
}
}
}
【讨论】:
我对 Android 游戏开发不太了解,但是在 Java2D 中(它有点 hacky 但它可以工作......)我会用编辑过的 JRE 类来 xboot 一个 jar,它控制渲染(例如 Canvas)到过程。
【讨论】:
This is a good read 在游戏循环中。它解释了游戏循环的各种实现和优缺点。
this is a good tutorial 在 Android 中实现 gameloop + FPS 计数器。
【讨论】: