我正在寻找一种在游戏应用程序中计算每秒帧数的方法,问题是我没有任何这些应用程序的源代码,他们没有在里面实现这样的功能。说实话,我真的不希望这是可能的,但值得一提。
非常清楚我明白我需要一个主要绘画循环的基本知识和代码来计算FPS。
最好的问候
答案 0 :(得分:1)
当你有一个主要的油漆循环时,进行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);
}
}
}
}
答案 1 :(得分:0)
我对Android游戏开发知之甚少,但是在Java2D中(它有点hacky但它的工作原理......)我会使用编辑后的JRE类来控制渲染(例如Canvas
进入过程。
答案 2 :(得分:0)
This is a good read。它解释了游戏循环的各种实现和优缺点。
和this is a good tutorial在Android中实现gameloop + FPS计数器。