2014-02-20 239 views
0

我有問題,我的限幅器的作品很不精確。我將每秒的目標幀數設置爲30,但我得到的值在10FPS和500FPS之間。我想我犯了一個很大的錯誤,但我無法找到它。 這是應該限制FPS類:這種方式Android OpenGL ES:每秒限制幀數

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 
} 

我很感激每一個幫助。

回答

1
System.currentTimeMillis(); 

這個功能是非常不精確的安卓(是discontinuos)使用,而不是:

SystemClock.elapsedRealtime(); 

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

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

無論你有什麼好的理由,我強烈建議不要在函數中使用sleep()。

我已經開發了很多Android遊戲,並且這些遊戲在幾乎所有Android設備上都運行良好。

走這條路。方向向量* Delta *值(這是一個物體應該在1秒內移動)

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

蜱是毫秒