how to set transformation matrices of transform
Hi,
I'm getting the world-to-local matrix of an object from an AR plugin I'm currently working on, now I try to apply the according transformation in Unity and I'm stuck. I noticed there is a Transform.worldToLocalMatrix property, but it only provides a getter. Also, I tried to find a way of decomposing the matrix into translation, rotation and scale, so I can set those accordingly, again letting Unity build the transformation matrix out of them, but again, I cannot find a way to do so, except for programming the decomposition by myself.
As I am not considering this - setting a transformation matrix - as a very uncommon thing to do, I am wondering: what is the recommended way to do it, what am I missing?
Thanks for your help.
There are a few old Q's that seem to cover this pretty well.
If so, I cannot find them. Which ones do you have in $$anonymous$$d?
Answer by iko79 · Jan 28, 2016 at 05:03 PM
Okay... here is what I apparently had to do, in case somebody is looking for a solution. Still looking for a better way for doing this, if there is one.
transform.localPosition = mat.GetColumn( 3 );
transform.localScale = new Vector3( mat.GetColumn( 0 ).magnitude, mat.GetColumn( 1 ).magnitude, mat.GetColumn( 2 ).magnitude );
float w = Mathf.Sqrt( 1.0f + mat.m00 + mat.m11 + mat.m22 ) / 2.0f;
transform.localRotation = new Quaternion( ( mat.m21 - mat.m12 ) / ( 4.0f * w ), ( mat.m02 - mat.m20 ) / ( 4.0f * w ), ( mat.m10 - mat.m01 ) / ( 4.0f * w ), w );
Answer by EvilTak · Jan 28, 2016 at 01:05 PM
If worldToLocal
is the Matrix4x4
that you are trying to set as the world to local matrix of a transform, simply assign its inverse to the Transform.localToWorldMatrix
variable. The local to world matrix of an object is always the inverse of the world to local matrix of that object, and vice versa.
Matrix4x4 worldToLocal = // Your matrix
theTransform.localToWorldMatrix = worldToLocal.inverse;
Yeah, well, no... I know that that's the inverse. However, both of them are read-only [1,2], at least in v5 they are. I read that while this is the most common thing to do in pure graphics engines such as OpenSceneGraph, in the case of Unity3D it wouldn't be a good idea to expose an interface for directly setting transformation matrices, since it would complicate many things, such as physics engine updates and what not. I'm just wondering what a good alternative is, since Unity also doesn't seem to provide utilities for, say, matrix decomposition. The $$anonymous$$atrix4x4 class is pretty sparse alltogether, frankly speaking.
[1] http://docs.unity3d.com/ScriptReference/Transform-localToWorld$$anonymous$$atrix.html
[2] http://docs.unity3d.com/ScriptReference/Transform-worldToLocal$$anonymous$$atrix.html
Hi, i need apply my own $$anonymous$$ATRIX4X4= 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] to my complete object, how can i do that?
Your answer
