Sign in to follow this  

Need help rotating about an arbitrary vector in OpenGL

This topic is 4574 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I've written the following function to rotate about an arbitrary vector (with non-zero components). Basically, I want to project the vector to the x-z plane, then to the z axis, then perform the rotation, and finally undo the rotations required to allign the vector to the z axis: void rotateArbitrary(float deg, float x, float y, float z) { float rad = degToRad(deg); // Rotation matrix for the rotation about the x, and z axis float rotateX[16]; float rotateY[16]; float rotateZ[16]; // Angles to rotate by float cosAlpha, sinAlpha, cosBeta, sinBeta; if(x > 0 && y > 0 && z > 0) { // The sine and cosine for the rotation about the x axis cosAlpha = z/sqrt(y*y + z*z); sinAlpha = y/sqrt(y*y + z*z); // The sine and cosine for the rotation about the y axis cosBeta = z/sqrt(x*x + z*z); sinBeta = x/sqrt(x*x + z*z); // Build up the rotation matrix // Rotate back about the x axis for 1 - alpha memset(rotateX, 0, sizeof(float) * 16); rotateX[0] = 1.0; rotateX[5] = cosAlpha; rotateX[9] = sinAlpha; rotateX[6] = -sinAlpha; rotateX[10] = cosAlpha; rotateX[15] = 1.0; glMultMatrixf(rotateX); // Rotate back about the y axis for 1 - beta memset(rotateY, 0, sizeof(float) * 16); rotateY[0] = cosBeta; rotateY[8] = -sinBeta; rotateY[5] = 1.0; rotateY[2] = sinBeta; rotateY[10] = cosBeta; rotateY[15] = 1.0; glMultMatrixf(rotateY); // Rotate the desired amount about the z axis memset(rotateZ, 0, sizeof(float) * 16); rotateZ[0] = cos(rad); rotateZ[4] = -sin(rad); rotateZ[1] = sin(rad); rotateZ[5] = cos(rad); rotateZ[10] = 1.0; rotateZ[15] = 1.0; glMultMatrixf(rotateZ); // Rotate through beta to the z axis memset(rotateY, 0, sizeof(float) * 16); rotateY[0] = cosBeta; rotateY[8] = sinBeta; rotateY[5] = 1.0; rotateY[2] = -sinBeta; rotateY[10] = cosBeta; rotateY[15] = 1.0; glMultMatrixf(rotateY); // Rotate through alpha to the x/z plane memset(rotateX, 0, sizeof(float) * 16); rotateX[0] = 1; rotateX[5] = cosAlpha; rotateX[9] = -sinAlpha; rotateX[6] = sinAlpha; rotateX[10] = cosAlpha; rotateX[15] = 1.0; glMultMatrixf(rotateX); } } However, when I call the function with: rotateArbitrary(30.0, 1.0, 0.0, 0.0); The result is different to if you call the standard: glRotatef(30.0, 1.0, 1.0, 1.0); It appears to be rotating the -30 degrees about the x axis, instead of 30 degrees. I've tried the rotation matrices on their own, and they seem to work fine. Any advice would be appreciated. Thanks

Share this post


Link to post
Share on other sites
Sign in to follow this