Created
May 16, 2019 08:08
-
-
Save ar-android/389e6c240e78d151d626058a75f1738f to your computer and use it in GitHub Desktop.
Game loop engine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package engine; | |
public class GameEngine implements Runnable{ | |
public static final int TARGET_FPS = 75; | |
public static final int TARGET_UPS = 30; | |
private final Window window; | |
private final Thread gameLoopThread; | |
private final Timer timer; | |
private final GameLogic gameLogic; | |
public GameEngine(String windowTitle, int width, int height, boolean vSync, GameLogic gameLogic) { | |
this.window = new Window(windowTitle, width, height, vSync); | |
this.gameLoopThread = new Thread(this, "GAME_LOOP_THREAD"); | |
this.timer = new Timer(); | |
this.gameLogic = gameLogic; | |
} | |
public void start(){ | |
String osName = System.getProperty("os.name"); | |
if (osName.contains("Mac")){ | |
gameLoopThread.run(); | |
}else{ | |
gameLoopThread.start(); | |
} | |
} | |
@Override | |
public void run() { | |
try { | |
init(); | |
gameLoop(); | |
}catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
private void init() throws Exception{ | |
window.init(); | |
timer.init(); | |
gameLogic.init(); | |
} | |
private void gameLoop(){ | |
float elapsedTime; | |
float accumulator = 0f; | |
float interval = 1f / TARGET_UPS; | |
while (!window.requestClose()) { | |
elapsedTime = timer.getElapsedTime(); | |
accumulator += elapsedTime; | |
input(); | |
while (accumulator >= interval){ | |
update(interval); | |
accumulator -= interval; | |
} | |
render(); | |
if(!window.isvSync()) { | |
sync(); | |
} | |
} | |
} | |
private void sync() { | |
float loopSlot = 1f / TARGET_FPS; | |
double endTime = timer.getLastLoopTime() + loopSlot; | |
while (timer.getTime() < endTime){ | |
try{ | |
Thread.sleep(1); | |
}catch (InterruptedException ie){ | |
ie.printStackTrace(); | |
} | |
} | |
} | |
private void render() { | |
gameLogic.render(window); | |
} | |
private void update(float interval) { | |
gameLogic.update(interval); | |
} | |
private void input() { | |
gameLogic.input(window); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment