Search code examples
javaframe-rategravity

Java Implementing A Working FPS System


I am coding a "Gravity Simulator" in java, which just includes a ball that has a x and y force.

The way I'm doing it at the moment (which is not working) is the following:

Rules of the program: 4 pixels count as 1 meter. the gravity is 9.8m/s^2, so earth gravity.

in my main class I have this:

public int sleepMilli = 17; //the thread will sleep 17 milliseconds after every execution
public double g = 9.8; //gravity

then, in the main loop I have this:

try {
            Thread.sleep(17);
        } catch (InterruptedException e) {
            System.out.println("Thread couldn't sleep.");
            e.printStackTrace();
        }

so. how would I go about implementing a working fps system into this "game" so it doesn't affect the movement speed of the ball?

If you want any more information provided, simply ask me to do so.


Solution

  • One common solution is make all your simulation methods take the amount of seconds that elapsed since the last frame as an argument. For example public void move(float secondsElapsed).

    Then, in that main thread, measure the time that elapsed since last frame using System.currentTimeMilis(), don't assume that Thread.sleep(17); will sleep for exactly 17 miliseconds.

    This has two advantages: 1) super easy change of desired FPS and 2) your objects will move at correct speeds even if the game FPS would drop.