In the case of game development and gaming industry, FPS matters a lot. The game quality measurement depends heavily on the FPS count. In simple words, the higher the FPS of the game, the better. The FPS of a game is dependent on the processing time for instructions and rendering.
It takes some time to execute the game loop once. Let's have a look at a sample implementation of FPS management inside a game loop:
long startTime; long endTime; public final int TARGET_FPS = 60; @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; long interval = (1000 - delta)/TARGET_FPS; try { Thread.sleep(interval); } catch(Exception ex) {} invalidate(); } }
In the preceding example, we first noted the time before execution (startTime
) of the loop and then noted down the time after the execution (endTime
). We then calculated the time taken for execution (delta
). We already know the amount of time (interval
) it should take to maintain a maximum frame rate. So, for the remaining time, we put the game thread to sleep before it executes again. This can be applied to a different game loop system as well.
While using SurfaceView
, we can declare the FPS system inside the game loop in the run()
method:
long startTime; long endTime; public final int TARGET_FPS = 60; @Override public void run() { Canvas gameCanvas = null; while(isGameRunning) { startTime = System.currentTimeMillis(); //clear canvas gameCanvas = null; try { //locking the canvas for screen pixel editing gameCanvas = currentHolder.lockCanvas(); //Update game state currentState.update(); //render game state currentState.render(gameCanvas); endTime = System.currentTimeMillis(); long delta = endTime - startTime; long interval = (1000 - delta)/TARGET_FPS; try { Thread.sleep(interval); } catch(Exception ex) {} } Catch(Exception e) { //Update game state without rendering (Optional) currentState.update(); } } }
In this process, we capped the FPS count and tried to execute the game loop on the predefined FPS. A major drawback in this system is this mechanism massively depends on hardware configuration. For a slow hardware system, which is incapable of running the loop on the predefined FPS, this system has no effect. This is because the interval time is mostly zero or less than zero, so there is no per frame cycle.
3.144.35.122