Hey all,
I’m having some issues with the delta-timing in my game engine. I’m basing it from some tutorial code I worked through, but I’ve found some cases where it’s bugging out a bit. Timing seems fine when there’s no load on the engine and the framerates are high, but when there’s a lot on the screen (during stress testing), the timing goes well out of whack.
For example, a movement along one axis of 1 unit per second somehow ends up as 50 units per second when the game is ‘laggy’ when under load.
Here’s the two key methods. First, the main game loop (N.B. the ‘delta’ static member of the encompassing class, so I can access it from elsewhere):
public void start()
{
lastFrame = getTime();
lastFPS = getTime();
delta = 0;
gameState = startupState;
// while the game is running we loop round updating and rendering
while (!Display.isCloseRequested() && !AppWin.ref.isClosedRequested())
{
// calculate the frame delta (time elapsed since the last loop iteration)
int _delta = (int) (getTime() - lastFrame);
lastFrame = getTime();
delta = _delta;
// clear the display
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_STENCIL_BUFFER_BIT);
// ensure a constant update speed
int remainder = delta % 10;
int step = delta / 10;
// run as many update cycles as we need to catch up to our render timing
for (int i=0;i<step;i++)
{
update(10);
}
if (remainder != 0)
{
update(remainder);
}
// render the game
render(delta);
// refresh the display
Display.update();
Display.sync(60);
// update the current FPS value
updateFPS();
}
Display.destroy();
System.exit(0);
}
And the timing function:
private long getTime()
{
return (Sys.getTime() * 1000) / Sys.getTimerResolution();
}
Here’s a typical example of how I use this delta value:
// what speed are we moving at, based on the current delta?
// 'forwardSpeed' will be a fixed value, such as 10
speed = (forwardSpeed * GameLoop.delta) / 1000f;
I’m clearly doing something wrong here, otherwise my application of the ‘speed’ variable would be predictable, regardless of frame rate.
Thanks for any insight anyone can offer