2012-05-26 53 views
1

我已經使用OpenGL創建了一個立方體,但此刻它有自由旋轉,因此它可以向任何方向旋轉。OpenGL Cube Rotation

我該如何編碼它,因此它只能向上,向下,向左和向右旋轉?

這裏是我的我的轉碼:

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

死亡的三角代碼牆!儘管如此,請儘量簡化您的問題,因爲在當前狀態下很難理解。 –

+0

我要的只是立方體只能在四個方向旋轉;向上,向下,向左,向右 –

+0

你的意思是每個旋轉周圍的軸應該只有90 * n度? –

回答

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, ... 

左右旋轉奧茲(我們假設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) | 

展開這些矩陣和yo的矢量相乘你會得到所需的旋轉,最小舍入誤差。

如果你想得到絕對精度,存儲原始的(x,y,z)向量,並且對於每個旋轉三元組(ax,ay,az)計算R矩陣(1和0)或者只記得這些矩陣表示基向量的偶數排列,因此您可以僅使用交換旋轉(x,y,z)。

還有一件事。如果您正在考慮立方體從一側到另一側的平滑旋轉,那麼您必須查找SLerp並使用某個動畫計時器插入Src-to-Dest旋轉。