Skip to content
Advertisement

How do i make my game not speed up/slow down depending on the fps in java?

So when I’m running a game I’m working on, the FPS will go up and down. But then so will the in game time. more fps, faster movement. less fps, slower movement. I’m using the javax.swing.Timer class with a 10ms delay and a personalized ActionListener class. Does anyone know how to get rid of these time conundrums? Something like Unity’s Time.deltaTime would be perfect, as that’s what I’m used to.

Advertisement

Answer

Record the time in your ActionListener class:

class MyActionListener implements ActionListener {
    private long previousStartTime = -1;
    

    @Override
    public void actionPerformed(ActionEvent e) {
        long now = System.currentTimeMillis();
        long elapsedTime = previousStartTime != -1 ? now - previousStartTime : 0;
        previousStartTime = now;
        
        // use elapsedTime
        // e.g.
        double pixelsToMove = speedPerMs * elapsedTime;
    }
}

On the first iteration the elapsedTime will be zero.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement