# Back and forth rotation on Y-axis

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; }


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);

• Thanks. I don't yet know how to obtain the time. I am using Windows 10. – Stackmm Mar 3 '18 at 5:47
• 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. – user1118321 Mar 3 '18 at 5:50
• If you want high precision time in the win32 API you can use QueryPerformanceCounter and QueryPerformanceFrequency – PaulHK Mar 3 '18 at 11:09
• Is it possible to do this using frame rate instead of time? – Stackmm Mar 4 '18 at 1:23
• 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. – user1118321 Mar 6 '18 at 2:28