Skip to content

Commit

Permalink
fixed deltatime
Browse files Browse the repository at this point in the history
  • Loading branch information
Pegacraft committed Feb 18, 2021
1 parent b63e110 commit 50714b4
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
4 changes: 2 additions & 2 deletions src/main/java/engine/Game.java
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,10 @@ public static Scene getScene(String alias) {

/**
*
* @return Returns the time it took, to show the last frame.
* @return How long it took to calculate the last frame in respect to the framerate
*/
public static double deltaTime() {
return (double) Loop.frameTime / 1000000;
return (double) Loop.frameTime / (1E9 / FPS);
}

/**
Expand Down
12 changes: 7 additions & 5 deletions src/main/java/engine/loops/Loop.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import engine.Entity;
import engine.Game;
import engine.Scene;
import engine.mechanics.EntityList;
import engine.rendering.Graphics;

import java.util.ConcurrentModificationException;
Expand All @@ -15,19 +14,22 @@ public class Loop implements Runnable {
/**
* the time it took to calculate the last frame in ns
*/
public static long frameTime = 1;
private static long calculationTime = 1;
public static int frameTime = 0;
private int frameRate = 60;
private boolean running = false;
private long lastFrame = System.nanoTime();

@Override
public void run() {
while (running) {
long startTime = System.nanoTime();
frameTime = (int) (System.nanoTime() - lastFrame);
long startTime = lastFrame = System.nanoTime();
logicLoop();
renderLoop();
try {
frameTime = (System.nanoTime() - startTime);
long toWait = (long) 1E9 / frameRate - frameTime;
calculationTime = (System.nanoTime() - startTime);
long toWait = (long) 1E9 / frameRate - calculationTime;
if (toWait < 0) toWait = 0;
//noinspection BusyWait
Thread.sleep((long) (toWait / 1E6), (int) (toWait % 1E6));
Expand Down

0 comments on commit 50714b4

Please sign in to comment.