I have created a cube using OpenGL, but at the moment it has free rotation so it rotates in any direction.
How can I code it so it only rotates up, down, left and right?
Here’s my my code for rotations:
+ (void)applyRotation:(GLfloat *)m x:(GLfloat)x y:(GLfloat)y z:(GLfloat)z {
GLfloat tempMatrix[16];
if(x != 0) {
GLfloat c = cosf(x);
GLfloat s = sinf(x);
[self applyIdentity:tempMatrix];
tempMatrix[5] = c;
tempMatrix[6] = -s;
tempMatrix[9] = s;
tempMatrix[10] = c;
[self multiplyMatrix:tempMatrix by:m giving:m];
}
if(y != 0) {
GLfloat c = cosf(y);
GLfloat s = sinf(y);
[self applyIdentity:tempMatrix];
tempMatrix[0] = c;
tempMatrix[2] = s;
tempMatrix[8] = -s;
tempMatrix[10] = c;
[self multiplyMatrix:tempMatrix by:m giving:m];
}
if(z != 0) {
GLfloat c = cosf(z);
GLfloat s = sinf(z);
[self applyIdentity:tempMatrix];
tempMatrix[0] = c;
tempMatrix[1] = -s;
tempMatrix[4] = s;
tempMatrix[5] = c;
[self multiplyMatrix:tempMatrix by:m giving:m];
}
}
“each rotation should be only 90*n degrees around one of the axes”
The rotation matrices in this case are almost trivial and consist only of zeros, ones and minus ones.
Rotation around Oz (we assume a = 90 * n):
Rotation around Ox:
Rotation around Oy:
Unroll the multiplication of vectors by these matrices and you will get the required rotations with minimal roundoff errors.
If you want the absolute precision, store the original (x,y,z) vector and for each rotation triple (ax, ay, az) calculate the R matrix (of ones and zeros) or just remember that these matrices represent the even permutations of the basis vectors so you can rotate the (x,y,z) with swaps only.
One more thing. If you’re thinking about smooth rotation from side to side of the cube, then you have to look for SLerp and interpolate the Src-to-Dest rotation using some animation timer.