Android OpenGL ES:每秒限制帧数

时间:2014-02-20 20:13:04

标签: android opengl-es opengl-es-2.0 frame-rate

我遇到的问题是我的帧限制器工作非常不精确。我将每秒的目标帧数设置为30,但是我得到的值在10FPS到500FPS之间。我想我犯了一个大错,但我找不到。 这是应该限制FPS的类:

public class FrameLimiter {

private long interval;
private long startTime;
private long endTime;
private long timeForOneFrame;

/** Limits an unlimited loop.
 * You should select a value above 25FPS!
 * @param FPS the target value of frames per second
 */
public FrameLimiter(int FPS){
    interval = 1000/FPS;
    startTime = System.currentTimeMillis();
}

/** Calling this method stops the current thread until enough time elapsed to reach the target FPS.
 */
public void limit(){
    endTime = System.currentTimeMillis();
    timeForOneFrame = endTime - startTime;

    if (timeForOneFrame < interval)
        try {
            Thread.sleep(interval - timeForOneFrame);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    startTime = System.currentTimeMillis();
}

/** Returns the current FPS measured against the time between two calls of limit().
 * This method just works in combination with limit()!
 * @return the current FPS.
 */
public int getFPS(){
    if(timeForOneFrame <= 0){
        return 0;
    }else{
        return (int) (1000/timeForOneFrame);
      }
  }
}

我这样用我的课:

@Override
public void onDrawFrame(GL10 gl) {            
    this.render();

    Log.d(toString(), String.valueOf(limiter.getFPS())+ "FPS");
    limiter.limit();    //has to be the last statment
}

我将非常感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

System.currentTimeMillis();

此功能在Android(不连续)中使用非常不精确:

SystemClock.elapsedRealtime();

SystemClock.sleep(millis); //not need try block, instead of 

Thread.sleep(millis);//need try block

答案 1 :(得分:0)

无论你有什么理由,我强烈建议你不要在函数中使用sleep()。

我在Android上开发了很多游戏,而且几乎所有的Android设备都运行良好。

走这条路吧。方向矢量* Delta * Value(对象应在1秒内移动)

Delta是(Tick - LastTick)/ 1000.f;

Tick是ms

相关问题