Newer
Older
AlgebraicDataflowArchitectureModel / GameEngine / src / main / java / gameEngine / Time.java
NoranekoFelician on 19 Nov 1 KB ・InputFieldを作成
package gameEngine;

public class Time {
    public static long timeStarted = System.nanoTime();
    private static long lastFrameTime = System.nanoTime();
    public static float deltaTime = 0;

    private static final long targetFrameTimeNanos = (long) (1E9 / 180); // <- フレームタイム
    private static long lastFpsCheckTime = System.nanoTime();
    private static int frameCount = 0;
    private static float currentFps = 0;

    public static float getTime() {
        return (float) ((System.nanoTime() - timeStarted) * 1E-9);
    }

    public static void update() {
        long currentTime = System.nanoTime();
        deltaTime = (float) ((currentTime - lastFrameTime) * 1E-9);
        lastFrameTime = currentTime;

        // FPSの計算
        frameCount++;
        if (currentTime - lastFpsCheckTime >= 1E9) {
            currentFps = frameCount / ((currentTime - lastFpsCheckTime) * 1E-9f);
            frameCount = 0;
            lastFpsCheckTime = currentTime;
            System.out.println("Current FPS: " + currentFps);
        }

        // フレームレート制限
        long elapsedTime = currentTime - lastFrameTime;
        if (elapsedTime < targetFrameTimeNanos) {
            try {
                Thread.sleep((targetFrameTimeNanos - elapsedTime) / 1_000_000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    public static void reset() {
        timeStarted = System.nanoTime();
        lastFrameTime = timeStarted;
        deltaTime = 0;
        lastFpsCheckTime = timeStarted;
        frameCount = 0;
        currentFps = 0;
    }
}