二维坐标轴旋转公式推导

unity3d:Matrix4x4矩阵位移,缩放,旋转_unity3d

设点M在原坐标系中的坐标为(x,y),对应向量的模为r,幅角为α.将坐标轴绕坐标原点,按照逆时针方向旋转角θ形成新坐标系,点M在新坐标系中的坐标为(如图2-4),则

unity3d:Matrix4x4矩阵位移,缩放,旋转_矩阵缩放_02

由此得到坐标轴的旋转的坐标变换公式

unity3d:Matrix4x4矩阵位移,缩放,旋转_Matrix_03

矩阵旋转公式推导


unity3d:Matrix4x4矩阵位移,缩放,旋转_矩阵旋转_04

unity3d:Matrix4x4矩阵位移,缩放,旋转_矩阵缩放_05


unity3d:Matrix4x4矩阵位移,缩放,旋转_unity3d_06

Matrix4x4矩阵

矩阵也是3D图形学一个重要的概念,在D3D里用的很平凡,但是U3D里好像都已经封装到各个Object上去了,所以很容易忽视掉,但不能忽视它的存在。在3D世界里,每个物体均有自身的世界矩阵,摄像机有摄像机矩阵,投影场景有projection矩阵,对顶点、向量、物体实施各种平移、旋转、缩放都是通过矩阵来完成的。计算机3D物体的标准4×4矩阵是这样定义的:(表示不出来矩阵大括号,请读者就当左4行的[和右4行的]当成一对大括号)
Transform:
这个就是U3D所封装的矩阵运算了,用于缩放,平移,还有定位(这个囧,他把矩阵给放这用了,所有物体都可以用transform类型来存放)。Transform所实现的功能不过就是物体矩阵的运算罢了,具体如下:

Matrix4x4中,是按列优先填充的。m12就是第一行二列,下标从0开始

//
// 摘要:
// A standard 4x4 transformation matrix.
[DefaultMember(“Item”)]
[NativeClass(“Matrix4x4f”)]
[NativeHeader(“Runtime/Math/MathScripting.h”)]
[NativeType(Header = “Runtime/Math/Matrix4x4.h”)]
[RequiredByNativeCode(Optional = true, GenerateProxy = true)]
[ThreadAndSerializationSafe]
public struct Matrix4x4 : IEquatable
{
[NativeName(“m_Data[0]”)]
public float m00;
[NativeName(“m_Data[15]”)]
public float m33;
[NativeName(“m_Data[14]”)]
public float m23;
[NativeName(“m_Data[13]”)]
public float m13;
[NativeName(“m_Data[12]”)]
public float m03;

unity3d:Matrix4x4矩阵位移,缩放,旋转_矩阵旋转_07

Matrix4x4.identity 单位矩阵
这个矩阵在使用的时不会影响任何东西。它的主对角线上全是1,其他位置全是0。

矩阵旋转

public static void Matrix4x4_Rotation(this Transform transform, SelfAxle axle, float angle)
{
Matrix4x4 ori = Matrix4x4.zero;
ori.SetTRS(transform.position, transform.rotation, Vector3.one);

matrix = Matrix4x4.identity;

if (axle == SelfAxle.X)
{
matrix.m11 = Mathf.Cos(angle * Mathf.Deg2Rad);
matrix.m12 = -Mathf.Sin(angle * Mathf.Deg2Rad);
matrix.m21 = Mathf.Sin(angle * Mathf.Deg2Rad);
matrix.m22 = Mathf.Cos(angle * Mathf.Deg2Rad);

}
else if (axle == SelfAxle.Y)
{
matrix.m00 = Mathf.Cos(angle * Mathf.Deg2Rad);
matrix.m02 = Mathf.Sin(angle * Mathf.Deg2Rad);
matrix.m20 = -Mathf.Sin(angle * Mathf.Deg2Rad);
matrix.m22 = Mathf.Cos(angle * Mathf.Deg2Rad);
}
else
{
matrix.m00 = Mathf.Cos(angle * Mathf.Deg2Rad);
matrix.m01 = -Mathf.Sin(angle * Mathf.Deg2Rad);
matrix.m10 = Mathf.Sin(angle * Mathf.Deg2Rad);
matrix.m11 = Mathf.Cos(angle * Mathf.Deg2Rad);
}


matrix = matrix * ori;
transform.rotation = matrix.GetRotation();
}

public static Quaternion GetRotation(this Matrix4x4 matrix4X4)
{
float qw = Mathf.Sqrt(1f + matrix4X4.m00 + matrix4X4.m11 + matrix4X4.m22) / 2;
float w = 4 * qw;
float qx = (matrix4X4.m21 - matrix4X4.m12) / w;
float qy = (matrix4X4.m02 - matrix4X4.m20) / w;
float qz = (matrix4X4.m10 - matrix4X4.m01) / w;
return new Quaternion(qx, qy, qz, qw);
}

//如何使用
transform.Matrix4x4_Rotation(SelfAxle.X, 46f);

源码

​https://github.com/luoyikun/UnityForTest​​ MatrixTest场景