# 【Unity矩阵知识】之Matrix4x4矩阵变换详细实例

unity3d 同时被 2 个专栏收录
12 篇文章 0 订阅
1 篇文章 0 订阅

## 标题 ##博主最近研究矩阵的成果，简单的封装了一下，可直接当成工具类调用：

MatrixUtils工具类

internal  static class MatrixUtils
{
public static void Matrix4x4(this Transform transfrom,Matrix4x4 matrix4X4)
{
transfrom.localScale = matrix4X4.GetScale();
transfrom.rotation = matrix4X4.GetRotation();
transfrom.position = matrix4X4.GetPostion();
}

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);
}

public static Vector3 GetPostion(this Matrix4x4 matrix4X4)
{
var x = matrix4X4.m03;
var y = matrix4X4.m13;
var z = matrix4X4.m23;
return new Vector3(x,y,z);
}

public static Vector3 GetScale(this Matrix4x4 m)
{
var x = Mathf.Sqrt(m.m00*m.m00 + m.m01*m.m01 + m.m02*m.m02);
var y = Mathf.Sqrt(m.m10*m.m10 + m.m11*m.m11 + m.m12*m.m12);
var z = Mathf.Sqrt(m.m20*m.m20 + m.m21*m.m21 + m.m22*m.m22);
return new Vector3(x,y,z);
}
}

Matrix封装类

internal static class Matrix
{
private static Matrix4x4 matrix;
public static void Matrix4x4_Transfrom(this Transform transform, Vector3 targetPos)
{
matrix = Matrix4x4.identity;
Vector4 v = new Vector4(transform.position.x, transform.position.y, transform.position.z, 1);

matrix.m03 = targetPos.x;
matrix.m13 = targetPos.y;
matrix.m23 = targetPos.z;

v = matrix * v;

transform.Matrix4x4(matrix);
}

public static void Matrix4x4_Rotation(this Transform transform, EnemyManager.Axle axle, float angle)
{
matrix = Matrix4x4.identity;

if (axle == EnemyManager.Axle.X)
{

}
else if (axle == EnemyManager.Axle.Y)
{
}
else
{
}

transform.Matrix4x4(matrix);
}

public static void Matrix4x4_Scale(this Transform transform, Vector3 targetScale)
{
matrix = Matrix4x4.identity;
Vector4 v = new Vector4(transform.localScale.x, transform.localScale.y, transform.localScale.z, 1);

matrix.m00 = targetScale.x;
matrix.m11 = targetScale.y;
matrix.m22 = targetScale.z;
v = matrix * v;
transform.Matrix4x4(matrix);
}
}

public  class Test :MonoBehaviour
{
void Start()
{
transform.Matrix4x4_Rotation(EnemyManager.Axle.X, 90f);//旋转
transform.Matrix4x4_Scale(new Vector3(2,2,2));//缩放
transform.Matrix4x4_Transfrom(new Vector3(6,6,6));//位移
}

}

• 7
点赞
• 6
评论
• 29
收藏
• 打赏
• 扫一扫，分享海报

09-08 4010
02-26 3494

05-28 267
12-20 5269
05-15 1513
12-23 7514
12-28 1015
07-30 2816
07-12 6087
11-17 1万+
08-31 165
04-19 770
05-27 1万+

_阿松先生

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。