2017-07-01 39 views
1

我正在嘗試創建一個小型應用程序,它可以隨着鼠標移動在一個立方體周圍旋轉相機。它可以完美地繞Y軸旋轉,但是我在繞X軸旋轉時遇到了問題。當我不斷向上移動鼠標時,立方體開始在正X方向旋轉。經過一段時間後,它反轉它的旋轉方向並開始在負X方向上旋轉,然後一段時間後再次沿正X方向旋轉。只要我向上移動鼠標,我想使它圍繞正X旋轉。這裏有什麼問題?相機旋轉方向逆轉一段時間後

立方體位於座標系的中心。投影角度:

編輯:這是涉及到的問題視頻:https://youtu.be/997ZdUM8fcQ

vec4 eye; 
vec4 at; 
vec4 up; 
GLfloat mouseX = -1; 
GLfloat mouseY = -1; 

// Bound to glutPassiveMotionFunc 
void mouse(int x, int y) { 
    // This rotation works perfect, cube rotates on same direction continuously as far as I move the mouse left or right 
    GLfloat acceleration_x = mouseX - x; 
    eye = RotateY(acceleration_x/10.f) * eye; 
    mouseX = x; 


    // This rotation doesn't work properly, after some time, cube's rotation direction inverses 
    GLfloat acceleration_y = mouseY - y; 
    eye = RotateX(acceleration_y/10.f) * eye; 
    mouseY = y; 


    // This part teleports pointer to opposite side of window after reaching window bounds 
    if (x >= 1364) { 
     glutWarpPointer(1, y); 
     mouseX = 1; 
    } 
    else if (x <= 0) { 
     glutWarpPointer(1363, y); 
     mouseX = 1363; 
    } 

    if (y >= 751) { 
     glutWarpPointer(x, 3); 
     mouseY = 3; 
    } 
    else if (y <= 2) { 
     glutWarpPointer(x, 750); 
     mouseY = 750; 
    } 
} 


void display(void) 
{ 
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 

    vec4 up(0.0, 1.0, 0.0, 0.0); 

    mat4 model_view = LookAt(eye, at, up); 
    glUniformMatrix4fv(ModelView, 1, GL_TRUE, model_view); 

    glDrawArrays(GL_TRIANGLES, 0, NumVertices); 
    glutSwapBuffers(); 
} 

// Bound to glutTimerFunc 
void timer(int id) 
{  
    glutPostRedisplay(); 
    glutTimerFunc(1000.f/60.f, timer, 0); 
} 

int main(int argc, char **argv) 
{ 
    ...... 
    ...... 

    eye = vec4(0, 0, 2, 0); 
    at = vec4(0, 0, 0, 0); 
    up = vec4(0.0, 1.0, 0.0, 0.0); 

    ..... 
    ..... 
} 

回答

1

這是因爲相機被翻轉。像這樣使用你的手:讓食指是dir,你的拇指是up(thumb =(0,1,0))。將您的索引器向前撥,然後向上撥拇指。現在,開始繞X旋轉你的手:你的食指開始指向下,而你的拇指向前(在此期間,thumb.y爲正)。當您將手旋轉90度時,食指指向下方,拇指向前(thumb.y爲0)。當你繼續旋轉時,你的拇指開始向前指向+(拇指變成負向)。

此時,LookAt函數將不會計算您想要的矩陣,因爲您希望up矢量指向下(如我們所說,thumb.y爲負數),但在代碼中,up矢量是一個常數(0,1,0),所以LookAt將計算一個具有正數的矩陣。up.y相機翻轉

一個解決方案可能是您註冊所需的旋轉角度,並旋轉相機矩陣(而不是dir)與這些角度