I grabbed this from the book I’m learning from.
public void run()
{
// this is the method that gets called when the thread is started.
// first we get the current time before the loop starts
long startTime = System.currentTimeMillis();
// start the animation loop
while (running)
{
// we have to make sure that the surface has been created
// if not we wait until it gets created
if (!holder.getSurface ().isValid())
continue;
// get the time elapsed since the loop was started
// this is important to achieve frame rate-independent movement,
// otherwise on faster processors the animation will go too fast
float timeElapsed = (System.currentTimeMillis () - startTime);
// is it time to display the next frame?
if (timeElapsed > FRAME_RATE)
{
// compute the next step in the animation
update();
// display the new frame
display();
// reset the start time
startTime = System.currentTimeMillis();
}
}
// run is over: thread dies
}
Does it account for lag correctly and is it optimal?
What I mean is, if the video cannot update 60 times per second will the update() be called 60x per second?
Thanks
The answer to this is no. At the beginning of every game loop, you calculate how long its been since your last game loop. You store this in “timeElapsed”.
From here, you compare this to “FRAME_RATE”. “FRAME_RATE” is a misleading name, because in your case, it’s not your frame rate. You want a frame rate of 60. In order to wait for the appropriate amount of time, FRAME_RATE should be 1000(milliseconds)/60(frames per second).
Now, at the beginning of every iteration, you take the elapsed time and test to see if it is time for the next frame. If it isn’t, you skip doing any actual processing or rendering, and you run the loop again.
When the elapsed time finally surpasses the FRAME_RATE (which is really the frame delay), you perform your processing and you render the frame. Ideally, the amount of time it takes to do this will be less than your frame delay, allowing your next iteration to start on schedule. As long as this is the case, update() and display() will be called about 60 times per second.
However, if the time it takes to render and process the frame is longer than your frame delay, then the next frame will be processed on the very next iteration, and it will be late. In this case, update() and display() will be called less than 60 times per second.