How to get relative transform between two objects?

Say I have objectA and objectB, I want the Transform value between them which may change all of position, rotation and scale. It is something like

new Transform(objectB.transform.matrix * objectA.trasform.matrix.inversed)

does Unity provide this kind of things that will give a simple Transform? If I get the transform matrix, how to apply it to GameObject.transform?

2 Answers

2

Not all Matrix4x4 results can be represented as a single TRS (translation, rotation, scaling) set. Consider what happens when a rotation operation is applied to an uneven scaling operation: the result is a “shear”, which cannot be compensated for using only a single TRS set. This is why a Transform can be converted to a Matrix4x4, but not the reverse.

Possibly useful:
There are several useful Unity functions that allow you to specify a Matrix4x4. For example, Graphics.DrawMesh provides a few versions that allow you to specify a Matrix4x4 as input.

Not sure about your situation, but you may be able to achieve the effect as you desire by simply changing the parent of the targetObject. If, for example, it starts as a child of objectB, simply making it a child of the objectA using Transform.SetParent with the worldPositionStays parameter set to false, should have the effect you’re looking for. The reason this would work is multiple TRS sets are applied via the new parent-hierarchy (and no-longer applied by the old .parent-hierarchy).

I need to apply this matrix: "transformation":[15,0,0,0,0,15,0,0,0,0,15,0,0,0,0,1] and apply it to a gameobject (.obj 3D MODEL )to obtain a new transformation. How can i do that? Thank you.

not sure why you want matrix. just make
GameObject middleGameObject; //and
Vector3 middlePos;

and in code (Update function) set :

middlePos = middleTransform.position;
middlePos.x = (ObjectA.transform.position.x + ObjectBtransform.position.x)/2;
//same for y and z
middleGameObject.position = middlePos;