I’ll leave the why and wherefore out of it as its kind of a long story. Let’s just say for my own edification I’m trying to get a better handle on matrices.
As part of that: say you wanted to recreate the rotation and scale part of a transform matrix. Say, also that you didn’t have the handy Matrix4x4.TRS method for creating such a matrix and all you had was the quaternion rotation and the vector3 scale (we’re not worrying about position as everything is sitting at the origin). So with that in mind, can you see what I’m doing wrong here:
Matrix4x4 CreateMatrix ()
{
Quaternion rot = transform.rotation;
Vector4 r0 = new Vector4(
1 - 2 * rot.y * rot.y - 2 * rot.z * rot.z,
2 * rot.x * rot.y - 2 * rot.z * rot.w,
2 * rot.x * rot.z + 2 * rot.y * rot.w,
0
);
Vector4 r1 = new Vector4(
2 * rot.x * rot.y + 2 * rot.z * rot.w,
1 - 2 * rot.x * rot.x - 2 * rot.z * rot.z,
2 * rot.y * rot.z - 2 * rot.x * rot.w,
0
);
Vector4 r2 = new Vector4(
2 * rot.x * rot.z - 2 * rot.y * rot.w,
2 * rot.y * rot.z + 2 * rot.x * rot.w,
1 - 2 * rot.x * rot.x - 2 * rot.y * rot.y,
0
);
Vector4 r3 = new Vector4(
0,0,0,1
);
Matrix4x4 rotMatrix = new Matrix4x4();
rotMatrix.SetRow(0, r0);
rotMatrix.SetRow(1, r1);
rotMatrix.SetRow(2, r2);
rotMatrix.SetRow(3, r3);
Vector3 scale = transform.localScale;
r0 = new Vector4(scale.x, 0, 0, 0);
r1 = new Vector4(0, scale.y, 0, 0);
r2 = new Vector4(0, 0, scale.z, 0);
r3 = new Vector4(0,0,0,1);
Matrix4x4 scaleMatrix = new Matrix4x4();
scaleMatrix.SetRow(0, r0);
scaleMatrix.SetRow(1, r1);
scaleMatrix.SetRow(2, r2);
scaleMatrix.SetRow(3, r3);
return scaleMatrix * rotMatrix;
}
I’ve checked, rechecked and tripple checked the math and even had someone else check it. It should be good and it is as long as I only rotate and scale uniformly. As soon as I rotate and apply a non-uniform scale I get this crazy skewing going on. It doesn’t matter what or how massive the non-uniform scale is. As soon as its applied the whole thing skews exactly the same way. The scaling still happens and the rotation still happens… just way off what they should be.
If you have any insight I would be very thankful.