3D相机移动和旋转

时间:2018-10-11 07:23:54

标签: 3d camera game-physics game-development

我有一个3D场景,其中有三个等距间隔的框,我希望相机能够围绕相机目标旋转并向任意方向移动,通常就像3D建模应用程序中的相机一样,但是我的设置仅在摄像机目标位于原点,每当我向任意方向移动摄像机时,摄像机的位置和摄像机目标都会正确平移到新位置,但是我的摄像机仍然围绕场景的原点旋转

下图显示了我的相机目标和坐标系原点处的旋转 enter image description here

下图显示了我的摄像机目标向左移动,但是摄像机相对于坐标系的原点旋转 enter image description here

以下是我在x / y平面上旋转和移动相机的代码:

if (event.type == SDL_MOUSEMOTION && leftMouseButtonPressed == true)
{

    New.x = event.button.x;
    New.y = event.button.y;

    delta = New - prev;


    if (delta.x != 0) {

        angleX = delta.x / 2.0f;

        rotMat = glm::mat4(1);
        rotMat =   glm::rotate(rotMat, glm::radians(angleX), up);
        cameraUp = glm::normalize(glm::vec4(up, 1) * rotMat);
        cameraRight = glm::normalize(glm::cross(cameraUp, cameraDirection));
        cameraPos = rotMat * glm::vec4(cameraPos, 1) ;
        cameraDirection = glm::normalize(cameraPos - cameraTarget);

        camera = glm::lookAt(cameraPos, cameraTarget, up);


    }





if (event.type == SDL_MOUSEMOTION && rightMouseButtonPressed == true)
{

    New.x = event.button.x;
    New.y = event.button.y;

    delta = New - prev;


    if (delta.x != 0) {

        delta.x /= 10.0f;

        translateMat = glm::mat4(1);
        translateMat = glm::translate(translateMat, cameraRight * delta.x);
        cameraPos = translateMat * glm::vec4(cameraPos, 1);
        cameraTarget = translateMat * glm::vec4(cameraTarget, 1) ;


        camera = glm::lookAt(cameraPos, cameraTarget , cameraUp);


    }

1 个答案:

答案 0 :(得分:1)

累积水平和垂直角度(偏航角和俯仰角);每次这些更改:

  • 使用yawPitchRoll函数创建并缓存旋转矩阵cameraRot
  • 使用此矩阵计算并缓存相机的前后方向:

    cameraDirection = cameraRot * glm::vec3(-1.0f, 0.0f, 0.0f);
    cameraUp = cameraRot * glm::vec3(0.0f, 1.0f, 0.0f);
    

    保存浮点精度问题,这些问题已经归一化。

  • 然后可以使用以下方法从目标中计算出摄像机的位置:

    cameraPos = cameraTarget - cameraDistance * cameraDirection;
    

    cameraDistance是目标到摄像机的距离。