We have already seen some ways of defining the FPS system. We have already discussed the major drawback of the system as well. So, we can manipulate the game loop according to the real-time FPS generated in the current game loop cycle:
long startTime; long endTime; public static in ACTUAL_FPS = 0; @Override public void onDraw(Canvas canvas) { if(isRunning) { startTime = System.currentTimeMillis(); //update and paint in game cycle MainGameUpdate(); //set rendering pipeline for updated game state RenderFrame(canvas); endTime = System.currentTimeMillis(); long delta = endTime - startTime; ACTUAL_FPS = 1000 / delta; invalidate(); } }
Now, let's have a look at the hybrid FPS system where we cap the maximum FPS to 60. Otherwise, the game can be manipulated through actual FPS:
long startTime; long endTime; public final int TARGET_FPS = 60; public static int ACTUAL_FPS = 0; @Override public void onDraw(Canvas canvas) { if(isRunning) { startTime = System.currentTimeMillis(); //update and paint in game cycle MainGameUpdate(); //set rendering pipeline for updated game state RenderFrame(canvas); endTime = System.currentTimeMillis(); long delta = endTime - startTime; //hybrid system begins if(delta < 1000) { long interval = (1000 - delta)/TARGET_FPS; ACTUAL_FPS = TARGET_FPS; try { Thread.sleep(interval); } catch(Exception ex) {} } else { ACTUAL_FPS = 1000 / delta; } invalidate(); } }
18.118.139.224