相机翻转问题

Ice*_*nix 5 c# xna

我正在使用XNA3.1引擎在C#中编写游戏.然而,我的相机问题很小,基本上我的相机在其转动时旋转超过180度时会"翻转"(当相机达到180度时,它似乎会翻转回0度).获取视图矩阵的代码如下:

Globals.g_GameProcessingInfo.camera.viewMat = Matrix.CreateLookAt(Globals.g_GameProcessingInfo.camera.target.pos, Globals.g_GameProcessingInfo.camera.LookAt, up);                //Calculate the view matrix
Run Code Online (Sandbox Code Playgroud)

所述Globals.g_GameProcessingInfo.camera.LookAt可变位置1单元直接在相机,相对于摄像机的转动的前面,而"向上"是用下面的函数得到的变量:

static Vector3 GetUp()      //Get the up Vector of the camera
{
    Vector3 up = Vector3.Zero;
    Quaternion quat = Quaternion.Identity;
    Quaternion.CreateFromYawPitchRoll(Globals.g_GameProcessingInfo.camera.target.rot.Y, Globals.g_GameProcessingInfo.camera.target.rot.X, Globals.g_GameProcessingInfo.camera.target.rot.Z, out quat);

    up.X = 2 * quat.X * quat.Y - 2 * quat.W * quat.Z;       //Set the up x-value based on the orientation of the camera
    up.Y = 1 - 2 * quat.X * quat.Z - 2 * quat.Z * quat.Z;   //Set the up y-value based on the orientation of the camera
    up.Z = 2 * quat.Z * quat.Y + 2 * quat.W * quat.X;       //Set the up z-value based on the orientation of the camera
    return up;      //Return the up Vector3
}
Run Code Online (Sandbox Code Playgroud)

Fil*_*unc 1

我在 OpenGL 中使用 gluLookAt 遇到了同样的问题。我用我自己的相机类解决了这个问题:

void Camera::ComputeVectors()
{
    Matrix4x4 rotX, rotZ;
    Quaternion q_x, q_y, q_z;
    Quaternion q_yx, q_yz;
    q_x.FromAngleAxis(radians.x, startAxisX);
    q_y.FromAngleAxis(radians.y, startAxisY);
    q_z.FromAngleAxis(radians.z, startAxisZ);
    q_yx = q_y * q_x;
    q_yx.ToMatrix(rotZ);
    q_yz = q_y * q_z;
    q_yz.ToMatrix(rotX);
    axisX = startAxisX;
    axisZ = startAxisZ; 
    axisX.Transform(rotX);
    axisZ.Transform(rotZ);
    axisY = axisX.Cross(axisZ);

    position = startPosition;
    position -= center;
    position.Transform(q_yx);
    position += center;
}
Run Code Online (Sandbox Code Playgroud)

它可能过于复杂,但是有效。axisY是你的向上向量。完整代码清单位于: http://github.com/filipkunc/opengl-editor-cocoa/blob/master/PureCpp/MathCore/Camera.cpp

希望能帮助到你。