1
$\begingroup$

I want to write code for a cube rotating 10 degrees back and forth on its y-axis in an OpenGL application. Right now I have this written in my display method, however it depends on processor speed, and it may be more complicated than it needs to be. I would like to make the code independent of processor speed.

GLfloat rot = 10;
GLfloat angle = 0, angle2 = 0, angle3 = 0;

if (angle < rot){
   glRotated(angle, 0, 1,0);                                  
   angle++;
}
else{
   if (angle2 < rot * 2 ){
     glRotated(rot - angle2, 0, 1, 0);      
     angle2++;
    }

else{
    if (angle3 < rot ){
     glRotated(-rot + angle3, 0, 1, 0);     
     angle3++;
    }

else{ angle = 0, angle2 = 0, angle3 = 0; }
$\endgroup$
1
$\begingroup$

In order to dissociate the rotation from the CPU speed, you need to use some sort of timing in your function. I recommend passing in a time value of some sort. The easiest thing is to pass in the number of seconds since the app started. How you do that depends on your particular OS, which you didn't specify.

Once you have a timing constant, you can generate a triangle wave to control the rotation. This formula will oscillate between 0 and 1 over time:

double rotation = 2.0 * fabs(fmod(time, 1.0) - 0.5);

You can make it go from 0 to 10 by multiplying the result by 10:

rotation *= 10.0;

Then you plug that into your glRotated() call:

glRotated(rotation, 0, 1, 0);

If you want to make the motion a little smoother, you could replace the triangle wave with a sine wave, like this:

double rotation = 0.5 * (sin(time * 2.0 * M_PI + M_PI / 2.0) + 1.0);
$\endgroup$
  • $\begingroup$ Thanks. I don't yet know how to obtain the time. I am using Windows 10. $\endgroup$ – Stackmm Mar 3 '18 at 5:47
  • $\begingroup$ I haven't dealt with Windows in a few years, but this question on Stack Overflow seems like it might have some good ideas. At least there are lots of different answers so one of them will probably do the trick. $\endgroup$ – user1118321 Mar 3 '18 at 5:50
  • $\begingroup$ If you want high precision time in the win32 API you can use QueryPerformanceCounter and QueryPerformanceFrequency $\endgroup$ – PaulHK Mar 3 '18 at 11:09
  • $\begingroup$ Is it possible to do this using frame rate instead of time? $\endgroup$ – Stackmm Mar 4 '18 at 1:23
  • 1
    $\begingroup$ When you multiply the rotation by 10 you're changing the amplitude of the rotation, but not the frequency. So it will rotate 10 degrees per second instead of 1 degree per second. If you want to also change the frequency to match, you should divide time by 10. Then you'll get 10 degrees per 10 seconds, which is still 1 degree per second. $\endgroup$ – user1118321 Mar 6 '18 at 2:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.