【问题标题】:How to rotateX or rotateZ view matrix around specified axis?如何围绕特定轴旋转或旋转视图矩阵?
【发布时间】:2020-07-08 05:50:42
【问题描述】:

我想旋转视图矩阵(我应该认为这代表相机位置)。

我已经成功使用Matrix4f#rotateY 围绕 Y 轴旋转视图矩阵。

但是,关于 rotateX,这需要目标位置在世界的 (0,0,0) 中心,我想围绕指定位置旋转视图矩阵。

我尝试如下旋转矩阵:

targetCenter = Vector3f(x, y, z)

viewMatrix
    .translate(targetCenter)
    .rotateX(rotation)
    .translate(targetCenter.mul(-1.0f))

但是,这会使渲染模型重复两次。 这是围绕指定轴旋转视图矩阵的正确方法吗?

编辑

  • 根据 Draykoon D 的回答,我已经用 Kotlin 实现了摄像头,谢谢
  • 我使用 JOML 作为库来操作 Matrix
fun Matrix4f.orbitBy(modelCenter: Vector3f, angleY: Float, angleX: Float, focalLength: Float) {
    // Setup both camera's view matrices
    val modelCenterCp = Vector3f(modelCenter)
    val recenter = Matrix4f().translate(modelCenterCp.mul(-1.0f)) //not needed if world origin
    val rotation = Matrix4f()
            .rotateY(angleY)
            .rotateX(angleX)
    val moveBack = Matrix4f().translate(modelCenter) //not needed if world origin
    val transfer = moveBack.mul(rotation).mul(recenter) //order from right to left

    val eye = Vector3f(0f, modelCenter.y, -focalLength).mulProject(transfer)
    val up = Vector3f(0f, 1f, 0f)
    this.setLookAt(eye, modelCenter, up)
} 

【问题讨论】:

    标签: matrix opengl lwjgl joml


    【解决方案1】:

    它在您的示例中有效,因为我认为您的目标等于世界原点。 如果要绕世界原点旋转,则不需要平移部分。如果它在某个点附近,它将成为强制性的。

    在计算视图矩阵时我喜欢使用的是在我的相机中保留 3 个值:

    • 相机位置(眼睛)
    • 相机目标(中心)
    • 相机 upVector(向上)

    如果你想绕着你的目标点旋转,你需要在你的眼睛和 upVector 上应用你的旋转,一旦完成,你可以使用 mat4 lookAt(eye, center, up) 重新计算 viewMatrix

    void orbitBy(float yaw, vec3 rotationCenter) {
         mat4 recenter = translate(mat4(1.0), -rotationCenter); //not needed if world origin
         mat4 rotation = rotateY(mat4(1.0), yaw); //can be replaced by glm::eulerAngleZXY(yaw, pitch, roll) ...
         mat4 moveBack = translate(mat4(1.0, rotationCenter)); //not needed if world origin
         mat4 transfo = moveBack * rotation * recenter; //order from right to left
         m_eye = transfo * m_eye;
         m_up = transfo * m_up; 
         m_viewMatrix = lookAt(m_eye, m_center, m_up);
    }
    

    我更喜欢这种方法,因为它为您提供了对调试非常有帮助的更简单的值

    【讨论】:

    • m_center 是在哪里定义的?和rotationCenter是一样的吗?
    • 由你决定,如果你想围绕你正在寻找的对象旋转,是的。 m_center 应该是你面对的位置,它可以是一个移动的物体(第三人称,相机跟随),一个放置在远处的点 * camera_dir(视频游戏中的 fps 相机)
    • 谢谢!对我来说前者是合适的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多