Newer
Older
AlgebraicDataflowArchitectureModel / GameEngine / src / main / java / gameEngine / Time.java
NoranekoFelician on 22 Nov 1 KB ・FPS値をTextで表示
  1. package gameEngine;
  2.  
  3. public class Time {
  4. public static long timeStarted = System.nanoTime();
  5. private static long lastFrameTime = System.nanoTime();
  6. public static float deltaTime = 0;
  7.  
  8. private static final long targetFrameTimeNanos = (long) (1E9 / 180); // <- フレームタイム
  9. private static long lastFpsCheckTime = System.nanoTime();
  10. private static int frameCount = 0;
  11. private static float currentFps = 0;
  12.  
  13. public static float getTime() {
  14. return (float) ((System.nanoTime() - timeStarted) * 1E-9);
  15. }
  16.  
  17. public static void update() {
  18. long currentTime = System.nanoTime();
  19. deltaTime = (float) ((currentTime - lastFrameTime) * 1E-9);
  20. lastFrameTime = currentTime;
  21.  
  22. // FPSの計算
  23. frameCount++;
  24. if (currentTime - lastFpsCheckTime >= 1E9) {
  25. currentFps = frameCount / ((currentTime - lastFpsCheckTime) * 1E-9f);
  26. frameCount = 0;
  27. lastFpsCheckTime = currentTime;
  28. }
  29.  
  30. // フレームレート制限
  31. long elapsedTime = currentTime - lastFrameTime;
  32. if (elapsedTime < targetFrameTimeNanos) {
  33. try {
  34. Thread.sleep((targetFrameTimeNanos - elapsedTime) / 1_000_000);
  35. } catch (InterruptedException e) {
  36. Thread.currentThread().interrupt();
  37. }
  38. }
  39. }
  40.  
  41. public static void reset() {
  42. timeStarted = System.nanoTime();
  43. lastFrameTime = timeStarted;
  44. deltaTime = 0;
  45. lastFpsCheckTime = timeStarted;
  46. frameCount = 0;
  47. currentFps = 0;
  48. }
  49.  
  50. public static int getFPS(){
  51. return (int)currentFps;
  52. }
  53. }