2015-12-20 40 views
2

我意识到这个问题之前在stackoverflow上有问题,但我还没有找到一个我完全理解的答案,所以我想我会得到一些特定于我的情况的帮助。如何在OpenGL中使用鼠标在相机中移动?

我基本上想要能够使用鼠标围绕Y轴旋转。以下是我用于实际旋转的功能(角度以度为单位)。

void CCamera::RotateY (GLfloat Angle) 
{ 
    RotatedY += Angle; 

    //Rotate viewdir around the up vector: 
    ViewDir = Normalize3dVector(ViewDir*cos(Angle*PIdiv180) 
        - RightVector*sin(Angle*PIdiv180)); 

    //now compute the new RightVector (by cross product) 
    RightVector = CrossProduct(&ViewDir, &UpVector); 
} 

由于我使用GLUT,我使用被动函数来获取光标的x,y坐标。然后在我的显示我有以下几点:

void display(void) { 
    ... 
    mouseDisplacement = mouseX - oldMouseX; 

    if (mouseDisplacement > 0) Camera.RotateY(-1.0*abs(mouseDisplacement)); 
    else if (mouseDisplacement < 0) Camera.RotateY(1.0*abs(mouseDisplacement)); 

    oldMouseX = mouseX; 
    glutWarpPointer(centerWindowX, centerWindowY); // move the cursor to center of window 
    ...  
} 

现在的问题是很明显的,因为显示功能运行60次第二,鼠标光标正好卡在中间,每当我尝试将其移动。如果我没有显示功能循环,旋转真的是滞后和东西。那么做这件事的正确方法是什么?

再次注意,我只是希望让相机使用鼠标左右移动。虽然如果我能够像正常的fps一样工作,它会非常棒,但它并不是真正必要的。

任何帮助,非常感谢。

回答

0

您可能需要使用glutPassiveMotionFunc一个自定义的回调处理鼠标位置增量:

void handlerFunc(int x, int y) 
{ 
    /* code to handle mouse position deltas */ 
} 

int main() 
{ 
    /* [...] */ 

    glutPassiveMotionFunc(handlerFunc); // before glutMainLoop. 

    /* [...] */ 

    return 0; 
} 

文档:glutPassiveMotionFunc

-

而且,我相信有一些问题与您三角洲计算。您应该计算当前光标位置和窗口中心之间的差异(光标将在每帧之后设置)。

mouseDisplacement = mouseX - centerWindowX;

下面是一些代码我在引擎用它来获得一个FPS相机(随意做出相应的调整):

void update(float delta) // delta is usually 1.0/60.0 
{ 
    // Mouse. 
    MouseState mouse = InputDevices.get_mouse_state(); 

    // - Movement 
    camera->yaw += camera->speed * mouse.dx * delta; 
    camera->pitch -= camera->speed * mouse.dy * delta; 

    // Regular FPS camera. 
    // TODO(Clem): Move this to a class. 

    // Clamp. 
    if (camera->pitch > math::PI_OVER_TWO) { 
     camera->pitch = math::PI_OVER_TWO - 0.0001f; 
    } 
    else if (camera->pitch < -math::PI_OVER_TWO) { 
     camera->pitch = -math::PI_OVER_TWO + 0.0001f; 
    } 

    float pitch = camera->pitch; 
    float yaw = camera->yaw; 

    // Spherical coordinates (r=1). 
    camera->forward.x = -sin(yaw) * cos(pitch); 
    camera->forward.y = -sin(pitch); 
    camera->forward.z = -cos(yaw) * cos(pitch); 

    camera->right.x = -cos(yaw); 
    camera->right.y = 0.0; 
    camera->right.z = sin(yaw); 

    camera->up = cross(camera->forward, camera->right); 

    camera->forward = normalize(camera->forward); 
    camera->right = normalize(camera->right); 
    camera->up = normalize(camera->up); 
} 
+0

我的坏没有说清楚。我已经在使用glutPassiveMotionFunc(...)来更新全局变量'mouseX'。问题出现在我想在相机周围移动时,鼠标居中在窗口中。 – Bazinga

+0

好的。我相信问题来自您的三角洲计算。您应该计算当前光标位置和窗口中心之间的差异(光标将在每帧之后设置)。 –

+0

感谢您花时间帮助我。我也尝试了你上面说的,通过对中心坐标进行位移。但是,由于我将光标更新为保持在中间,所以位移总是为0或非常接近于0.因此,不应该像移动摄像机那样移动摄像机。 – Bazinga