c – 四元数到方向向量

我试图将我的四元数转换为方向向量,这样我就可以朝着它面向的方向移动我的相机.我读到你可以先将四元数转换为旋转矩阵然后得到方向,所以我试过了.

inline Matrix4<float> ToRotationMatrix() {
    Vector3<float> forward = Vector3<float>( 2.0f * ( GetX() * GetZ() - GetW() * GetY() ), 2.0f * ( GetY() * GetZ() + GetW() * GetX() ), 1.0f - 2.0f * ( GetX() * GetX() + GetY() * GetY() ) );
    Vector3<float> up = Vector3<float>( 2.0f * ( GetX() * GetY() + GetW() * GetZ() ), 1.0f - 2.0f * ( GetX() * GetX() + GetZ() * GetZ() ), 2.0f * ( GetY() * GetZ() - GetW() * GetX() ) );
    Vector3<float> right = Vector3<float>( 1.0f - 2.0f * ( GetY() * GetY() + GetZ() * GetZ() ), 2.0f * ( GetX() * GetY() - GetW() * GetZ() ), 2.0f * ( GetX() * GetZ() + GetW() * GetY() ) );

    return Matrix4<float>().InitRotationFromVectors( forward, up, right );
}

inline Matrix4<T> InitRotationFromVectors( const Vector3<T> &n, const Vector3<T> &v, const Vector3<T> &u ) {
    Matrix4<T> ret = Matrix4<T>().InitIdentity();

    ret[ 0 ][ 0 ] = u.GetX();
    ret[ 1 ][ 0 ] = u.GetY();
    ret[ 2 ][ 0 ] = u.GetZ();

    ret[ 0 ][ 1 ] = v.GetX();
    ret[ 1 ][ 1 ] = v.GetY();
    ret[ 2 ][ 1 ] = v.GetZ();

    ret[ 0 ][ 2 ] = n.GetX();
    ret[ 1 ][ 2 ] = n.GetY();
    ret[ 2 ][ 2 ] = n.GetZ();

    return ret;
}

inline Vector3<float> GetForward( const Matrix4<float> &rotation ) const {
    return Vector3<float>( rotation[ 2 ][ 0 ], rotation[ 2 ][ 1 ], rotation[ 2 ][ 2 ] );
}

当我的相机朝前时,它会以正确的方向移动,但是当我转动相机时,相机开始向不正确的方向移动.相机像这样旋转.

void Camera::Rotate( const Vector3<float> &axis, float angle ) {
    Rotate( Quaternion( axis, angle ) );
}

void Camera::Rotate( const Quaternion &quaternion ) {
    m_rotation = Quaternion( ( quaternion * m_rotation ).Normalized() );
}

并增加那些四元数….

inline Quaternion operator*( const Quaternion &quat ) const {
    Quaternion ret;

    ret[ 3 ] = ( ( *this )[ 3 ] * quat[ 3 ] ) - ( ( *this )[ 0 ] * quat[ 0 ] ) - ( ( *this )[ 1 ] * quat[ 1 ] ) - ( ( *this )[ 2 ] * quat[ 2 ] );
    ret[ 0 ] = ( ( *this )[ 3 ] * quat[ 0 ] ) + ( ( *this )[ 0 ] * quat[ 3 ] ) + ( ( *this )[ 1 ] * quat[ 2 ] ) - ( ( *this )[ 2 ] * quat[ 1 ] );
    ret[ 1 ] = ( ( *this )[ 3 ] * quat[ 1 ] ) + ( ( *this )[ 1 ] * quat[ 3 ] ) + ( ( *this )[ 2 ] * quat[ 0 ] ) - ( ( *this )[ 0 ] * quat[ 2 ] );
    ret[ 2 ] = ( ( *this )[ 3 ] * quat[ 2 ] ) + ( ( *this )[ 2 ] * quat[ 3 ] ) + ( ( *this )[ 0 ] * quat[ 1 ] ) - ( ( *this )[ 1 ] * quat[ 0 ] );

    return ret;
}

注意:Quaternion [0]是x,Quaternion [1]是y,Quaternion [2]是z,Quaternion [3]是w.

几个星期以来,我一直在努力解决这个问题.如果任何人对于其工作原理或其他方法有任何想法或建议,我们将不胜感激.谢谢!

最佳答案 所以让我们改写你想要做的事情:你有一个相机在全局帧中的位置G_p1的表示,并希望在它自己的帧中向前移动一个量C_t = [0; 0; 1](这里,G_前缀表示全局帧,C_表示相机).

我们想要计算G_p2 = G_p1 G_t.我们需要用C_t来编写G_t.

我们可以将其写为G_t = G_R_C C_t,其中G_R_C是描述从摄像机到全局帧的旋转的旋转矩阵.将其写为四元数q的函数,您只需计算G_t = G_R_C(q)C_t并将其添加到位置.因为C_t = [0; 0; 1],您可以看到G_t是G_R_C(q)的最后一列.您正在使用最后一行,而不是最后一列.

点赞