Saturday, July 15, 2017

glut - How to get and use delta time


I have mice looking and walking in my game, but they are very slow and hard to use. I think it's because I'm using fixed speed. I heard that in big projects developers use delta time. How do I calculate delta time in glut? How do I calculate speed using delta time?



Answer



The "delta time" used to be the time elapsed between two frame updates (but it can also be used in other contexts; this is usually the result of a time subtraction).


You can get the delta time in glut using the glutGet method and the GLUT_ELAPSED_TIME parameter, plus some operations.

The following line returns the number of milliseconds since glutInit was called (or first call to glutGet(GLUT_ELAPSED_TIME)) :



int timeSinceStart = glutGet(GLUT_ELAPSED_TIME);

So if you register the current timeSinceStart at each rendering loop, you can know the deltaTime by subtracting the old one to the new one.


int oldTimeSinceStart = 0;

while( ... )
{
int timeSinceStart = glutGet(GLUT_ELAPSED_TIME);
int deltaTime = timeSinceStart - oldTimeSinceStart;
oldTimeSinceStart = timeSinceStart;


//... stuff to update using deltaTime
}



You can also do it almost the same way, using the C/C++ ctime library with clock() and the macro constant expression CLOCKS_PER_SEC that specifies the relation between a clock tick and a second.




Basically, you can use deltaTime to update your movements in ratio to this elapsed time instead of using a fixed time value. This way, the movement speed of your character should be almost the same if your program runs at 60 fps or if it runs at 10 fps.



Here is a small example: suppose you want to move something by 10 units each second on the x axis. You could do something like this (if deltaTime use milliseconds indeed).



Position.x += 10/1000 * deltaTime;

This way, whether your program updated 2 times or 100 times, 1 second later the position should be almost the same, and the game-play is less impacted by the low fps of a small computer than if it use fixed values.




  • With fixed values ==> low fps = less updates = slow movements whereas high fps = more updates = very fast movements.




  • With deltaTime ==> "almost" the same movements.







Finally, you should read Fixed time step vs Variable time step on gamedev.stackexchange.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...