Hello everyone.
I’m working with importing an external 3D format into objects in Unity, and have hit a stumbling block on the matrix conversion.
I’m reading in a matrix from this format: LDraw.org - LDraw File Format Specification
e.g. 1 0 0 0 1 0 0 0 1
is the identity matrix.
The problem is that some matrix values, mainly with negative values are given a very wrong scale value.
// Convert the matrix into Unity objects
Matrix4x4 rotationMatrix = new Matrix4x4 (
new Vector4 (matrixTokens[0], matrixTokens[3], matrixTokens[6], 0),
new Vector4 (matrixTokens[1], matrixTokens[4], matrixTokens[7], 0),
new Vector4 (matrixTokens[2], matrixTokens[5], matrixTokens[8], 0),
new Vector4 (positionTokens[0], positionTokens[1], positionTokens[2], 1)
);
Vector3 position = new Vector3 (rotationMatrix.m03, -rotationMatrix.m13, rotationMatrix.m23); // -Y is up
Quaternion rotation = rotationMatrix.rotation;
Vector3 scale = rotationMatrix.lossyScale;
A simple scaling matrix of 6 0 0 0 -4 0 0 0 6
is generating a scale value of (-6.0, 4.0, 6.0)
instead of (6.0, -4.0, 6.0)
(Note the X scale is negative, not the Y), with no rotation((0, 0, 0)
).
Full matrix:
6.00000 0.00000 0.00000 0.00000
0.00000 -4.00000 0.00000 0.00000
0.00000 0.00000 6.00000 0.00000
0.00000 0.00000 0.00000 1.00000
I understand the scale is not guaranteed to be a perfect mapping (lossy), but this seems way too simple for it to be getting wrong.
Checking another object that has a matrix of 1 0 0 0 -5 0 0 0 1
ends up with a scale of (-1.0, 5.0, 1.0)
, but a Euler rotation of (0, -90, 180)
.
Can anyone see if I’m missing anything obvious here, or can recommend a way to get the appropriate scaling value from the matrix?
(Full code in guthub: VLD/Assets/Scripts/LDrawPart.cs at master · DeeHants/VLD · GitHub)
Many thanks.