OpenGL立方体旋转

时间:2012-05-26 15:43:14

标签: iphone ios opengl-es rotation

我使用OpenGL创建了一个立方体,但目前它有自由旋转,所以它可以向任何方向旋转。

我如何对其进行编码,使其仅向上,向下,向左和向右旋转?

这是我的旋转代码:

    + (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];
    }
    }

1 个答案:

答案 0 :(得分:0)

“每个旋转应该只围绕其中一个轴旋转90 * n度”

在这种情况下,旋转矩阵几乎是微不足道的,只包含零,一和零。

sin(90 * n) = 0, 1, 0, -1, 0, 1, 0, -1, ...
cos(90 * n) = 1, 0, -1, 0, 1, 0, -1, 0, ...

围绕Oz旋转(我们假设a = 90 * n):

| cos(a)  -sin(a)   0 |
| sin(a)   cos(a)   0 | 
|  0        0       1 |

围绕牛的旋转:

|   1      0      0    |
|   0    cos(a) sin(a)  |
|   0   -sin(a) cos(a)  |

围绕Oy旋转:

|  cos(a)   0   sin(a)  |
|   0       1     0    |
|  -sin(a)  0   cos(a)  |

通过这些矩阵展开向量的乘法,您将获得所需的旋转,并且最小的舍入误差。

如果你想要绝对精度,存储原始(x,y,z)向量,对于每个旋转三元组(ax,ay,az)计算R矩阵(1和0)或者只记住这些矩阵代表基矢量的偶数排列,因此您可以仅使用交换旋转(x,y,z)。

还有一件事。如果您正在考虑从立方体的一侧到另一侧的平滑旋转,那么您必须寻找SLerp并使用一些动画计时器插入Src-to-Dest旋转。