Created
April 1, 2020 09:48
-
-
Save openroomxyz/02d818d049e36ed62e8be42f1aab4c61 to your computer and use it in GitHub Desktop.
Unity : How to rotate,scale, translate with matrix?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static Matrix4x4 RotateX(float aAngleRad) | |
{ | |
Matrix4x4 m = Matrix4x4.identity; // 1 0 0 0 | |
m.m11 = m.m22 = Mathf.Cos(aAngleRad); // 0 cos -sin 0 | |
m.m21 = Mathf.Sin(aAngleRad); // 0 sin cos 0 | |
m.m12 = -m.m21; // 0 0 0 1 | |
return m; | |
} | |
public static Matrix4x4 RotateY(float aAngleRad) | |
{ | |
Matrix4x4 m = Matrix4x4.identity; // cos 0 sin 0 | |
m.m00 = m.m22 = Mathf.Cos(aAngleRad); // 0 1 0 0 | |
m.m02 = Mathf.Sin(aAngleRad); //-sin 0 cos 0 | |
m.m20 = -m.m02; // 0 0 0 1 | |
return m; | |
} | |
public static Matrix4x4 RotateZ(float aAngleRad) | |
{ | |
Matrix4x4 m = Matrix4x4.identity; // cos -sin 0 0 | |
m.m00 = m.m11 = Mathf.Cos(aAngleRad); // sin cos 0 0 | |
m.m10 = Mathf.Sin(aAngleRad); // 0 0 1 0 | |
m.m01 = -m.m10; // 0 0 0 1 | |
return m; | |
} | |
public static Matrix4x4 Rotate(Vector3 aEulerAngles) | |
{ | |
var rad = aEulerAngles * Mathf.Deg2Rad; | |
return RotateY(rad.y) * RotateX(rad.x) * RotateZ(rad.z); | |
} | |
public static Matrix4x4 Scale(Vector3 aScale) | |
{ | |
var m = Matrix4x4.identity; // sx 0 0 0 | |
m.m00 = aScale.x; // 0 sy 0 0 | |
m.m11 = aScale.y; // 0 0 sz 0 | |
m.m22 = aScale.z; // 0 0 0 1 | |
return m; | |
} | |
public static Matrix4x4 Translate(Vector3 aPosition) | |
{ | |
var m = Matrix4x4.identity; // 1 0 0 x | |
m.m03 = aPosition.x; // 0 1 0 y | |
m.m13 = aPosition.y; // 0 0 1 z | |
m.m23 = aPosition.z; // 0 0 0 1 | |
return m; | |
} | |
public static Matrix4x4 TRS(Vector3 aPos, Vector3 aEuler, Vector3 aScale) | |
{ | |
return Translate(aPos) * Rotate(aEuler) * Scale(aScale); | |
} | |
var pos = new Vector3(2, 5, -7); | |
var euler = new Vector3(20, 45, 10); | |
var scale = new Vector3(20, 15, 5); | |
var m1 = Matrix4x4.TRS(pos, Quaternion.Euler(euler), scale); | |
var m2 = TRS(pos, euler, scale); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment