matthew3r matthew3r - 3 months ago 25
C++ Question

c++ - OpenGL movement with deltatime

So, I started programming again in C++ and trying things out with OpenGL. Currently I have a basic application where I just want to move the camera with keys. I read many article about this, but still I have problem with the movement, I guess because even if only a little, but they differs from my program. First I made a 60 fps limit and calculated the speed with deltatime, but the movement was laggy. Now I turned off FPS limiting, but now it runs at around 4000 FPS, so deltatime is most of the time 0 or 1, so the movement is really really slow. I'm sure I don't understand something about the concept, but I need to point it out.

The main loop:

while (running) {
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {

if (msg.message == WM_QUIT) {
running = false;

break;
} else {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
} else {
clock_t last = clock();
deltaTime = last-start;

//if ((double)deltaTime >= 16.666666666) {
fps++;
millis += deltaTime;
start = last;

if (millis > 1000) {
millis = 0;
std::cout << "FPS: " << fps << std::endl;
fps = 0;
}

openglContext.renderScene();
//}
}
}


WndProc key handler:

float speed = 5.0f;

...

case WM_KEYDOWN:
switch(wParam) {
case 0x57:
openglContext.updateCoordinates(0.0f, 0.0f, ((float)deltaTime / 1000.0f * speed), glm::radians(angle));
break;
}
break;


I know it's not perfect, but as I wrote before I tried many "solutions".
Hope someone can help. Thanks in advance!

Solution:

There is still many to do, but for now it's perfect.

LARGE_INTEGER start;
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&start);

while (running) {

...

LARGE_INTEGER current;
QueryPerformanceCounter(&current);
dt = ((double)(current.QuadPart - start.QuadPart) / (double)frequency.QuadPart);
QueryPerformanceCounter(&start);

... key handling
... render
...

BDL BDL
Answer

The problem that delta_time is either 0 or 1 happens because of the generally low resolution of std::clock(). In most cases, the minimal time that can be measured is around 0.01 seconds, which is way to less for a rendering application. Reference

Depending on your system and on the compiler used, there are several alternatives that will allow you to measure timings with higher precision.

Comments