如何从Matrix4x4计算XYZ角度

时间:2014-02-02 20:26:19

标签: c# vector matrix angle decomposition

我试图通过分解矩阵来确定矩阵中保持的X,Y,Z角。我正在使用.net 4.5 c#。

我创建了一个测试来检查以下内容:

  • 如果我创建仅带有标识值的Matrix4x4
  • 将矩阵旋转45度
  • 分解矩阵并评估返回的四元数(给出x,y,z角度)
  • 检查X值是否与放入的45度相匹配

我得到以下结果: X:0.5 Y:0 Z:0

我在期待: X:0.45 Y:0 Z:0

测试代码

Quaternion quatDecomposed;
Vector3D translation;

Matrix4x4 rot = Matrix4x4.RotationAroundX(45);
rot.DecomposeNoScaling(out quatDecomposed, out translation);

我创建了自己的Matrix4x4,Vector3D和Angle3D结构,如下例所示。

我的Matrix4x4围绕x方法旋转如下:

    public static Matrix4x4 RotationAroundX(double degrees)
    {
        // [1, 0,  0,   0]
        // [0, cos,-sin,0]
        // [0, sin,cos, 0]
        // [0, 0,  0,   1]

        // convert degrees to radians.
        double radians = DoubleExtensions.DegreesToRadians(degrees);

        // return matrix.
        var matrixTransformed = Matrix4x4.Identity;

        matrixTransformed.M22 = (float)Math.Cos(radians);
        matrixTransformed.M23 = (float)-(Math.Sin(radians));

        matrixTransformed.M32 = (float)Math.Sin(radians);
        matrixTransformed.M33 = (float)Math.Cos(radians);

        //return matrix;
        return matrixTransformed;
    }

我的分解无缩放方法如下:

    public void DecomposeNoScaling(out Quaternion rotation, out Vector3D translation)
    {
        translation.X = this[1, 4];
        translation.Y = this[2, 4];
        translation.Z = this[3, 4];

        rotation = new Quaternion(new Matrix3x3(this));
    }

我希望得到的是Matrix4x4中包含的角度,我这样做如下:

Angle3D angles = new Angle3D(quatDecomposed.X, quatDecomposed.Y, quatDecomposed.Z);

有人能发现我做错了吗?我真正想要解决的是ZYX顺序中矩阵4x4的欧拉角。

提前致谢!

2 个答案:

答案 0 :(得分:0)

不应该是矩阵的最后一行是“1”?

[1 0 0 0]

[0 cos -sin 0]

[0 sin cos 0]

[0 0 0 1]

(最后一行最后一列应为1)

答案 1 :(得分:0)

以防万一其他人需要知道,这就是我直接从矩阵中得到欧拉角的方法:

    public static Angle3D GetAngles(Matrix4x4 source)
    {
        double thetaX, thetaY, thetaZ = 0.0;
        thetaX = Math.Asin(source.M32);

        if (thetaX < (Math.PI / 2))
        {
            if (thetaX > (-Math.PI / 2))
            {
                thetaZ = Math.Atan2(-source.M12, source.M22);
                thetaY = Math.Atan2(-source.M31, source.M33);
            }
            else
            {
                thetaZ = -Math.Atan2(-source.M13, source.M11);
                thetaY = 0;
            }
        }
        else
        {
            thetaZ = Math.Atan2(source.M13, source.M11);
            thetaY = 0;
        }

        // Create return object.
        Angle3D angles = new Angle3D(thetaX, thetaY, thetaZ);

        // Convert to degrees.;
        angles.Format = AngleFormat.Degrees;

        // Return angles.
        return angles;
    }