2011-12-15 53 views
0

我在OpenGL中讓我的對象(行星)相對於當前相機旋轉旋轉時出現問題。它起初似乎起作用,但是在旋轉一點之後,旋轉不再正確/相對於相機。在OpenGL中相對於相機旋轉對象

我正在計算屏幕上鼠標X和鼠標Y移動的增量(差異)。旋轉存儲在稱爲'planetRotation'的Vector3D中。

這裏是我的代碼相對旋轉來計算的planetRotation:

Vector3D rotateAmount; 
rotateAmount.x = deltaY; 
rotateAmount.y = deltaX; 
rotateAmount.z = 0.0; 

glPushMatrix(); 
    glLoadIdentity(); 
    glRotatef(-planetRotation.z, 0.0, 0.0, 1.0); 
    glRotatef(-planetRotation.y, 0.0, 1.0, 0.0); 
    glRotatef(-planetRotation.x, 1.0, 0.0, 0.0); 
    GLfloat rotMatrix[16]; 
    glGetFloatv(GL_MODELVIEW_MATRIX, rotMatrix); 
glPopMatrix(); 

Vector3D transformedRot = vectorMultiplyWithMatrix(rotateAmount, rotMatrix); 
planetRotation = vectorAdd(planetRotation, transformedRot); 

在理論上 - 這樣做是什麼,建立在「rotateAmount」可變旋轉。然後,通過將該向量與逆模型變換矩陣(rotMatrix)相乘,將其獲取到模型空間中。

然後將此轉換的旋轉添加到當前旋轉。

爲了使這是轉換爲設置:

glPushMatrix(); 
    glRotatef(planetRotation.x, 1.0, 0.0, 0.0); 
    glRotatef(planetRotation.y, 0.0, 1.0, 0.0); 
    glRotatef(planetRotation.z, 0.0, 0.0, 1.0); 
    //render stuff here 
glPopMatrix(); 

相機那種圍繞擺動,我試圖進行旋轉,似乎並不相對於當前變換。

我在做什麼錯?

回答

5

GAH!不要這樣做:

glPushMatrix(); 
    glLoadIdentity(); 
    glRotatef(-planetRotation.z, 0.0, 0.0, 1.0); 
    glRotatef(-planetRotation.y, 0.0, 1.0, 0.0); 
    glRotatef(-planetRotation.x, 1.0, 0.0, 0.0); 
    GLfloat rotMatrix[16]; 
    glGetFloatv(GL_MODELVIEW_MATRIX, rotMatrix); 
glPopMatrix(); 

OpenGL不是一個數學庫。這種工作有適當的線性代數庫。


至於你的問題。 一個向量不適合存儲旋轉。你至少需要一個Vector(旋轉軸)和角度本身,或者更好的是四元數。

此外,旋轉不添加。它們不是交換的,但是另外一個交換操作。實際上旋轉乘以

如何修復代碼:使用適當的數學方法從頭開始重寫。爲此,請閱讀「旋轉矩陣」和「四元數」(維基百科有它們)的主題。