Combining matrices

I have a problem. I’m trying to get a local position in one transform into a local position of another transform. And what I normally do isn’t working. Normally I would just multiply matrices together, to create a new matrix. In this case I’m doing this:

Matrix4x4 localToLocal = transform1.localToWorldMatrix*transform2.worldToLocalMatrix;

Now, if I do it in two steps, it works:

Vector3 newLocalPosition = transform1.localToWorldMatrix.MultiplyPoint(position);
newLocalPosition = transform2.worldToLocalMatrix.MultiplyPoint(newLocalPosition );

Method 1 works if there is no rotation involved. But as soon as I rotate, things gets weird.

Why doesn’t it work with the combined matrix? It is fine by me to just do it in two steps, but I have obviously misunderstood something crucial here, since I can’t get method 1 to work…

maybe i’m doing it wrong but i had never to work with matrices manually in unity. instead i would use Transform.TransformDirection and InverseTransformDirection.

Have you tried using transform.TransormPoint and inverseTransformPoint, bypasses the need to do any matrix math on your part

The matrix multiplication order is inverted:

Matrix4x4 localToLocal = transform2.worldToLocalMatrix * transform1.localToWorldMatrix;
1 Like

Dantus. Thanks! It works…:slight_smile:

exiguous: Well, first of all the ones you show here have to do with directions, not positions. Second of all it only takes you from either worldToLocal, or from localToWorld. Not from one objects local space, to another objects local space. To do this in one go you have to combine matrices from each object. But as you can see I do indeed just use the matrices offered by the transform components. I just tried to combine them :slight_smile: And did it wrong…

hpjohn: Again, those two function will only take you from an objects local space, and into world space, or the inverse. It won’t take me from one objects local space, to another objects local space.

Thanks for all your help, sorry for late reply. I actually just changed it to do it in two steps after this thread was created, and forgot I ever asked the question. I’m so much more happy now, as I’m back to doing it in one go (thx Dantus!)