How to calculate the new transform values relative to parent?

What’s the math formula to use when calculating the new transform (position, rotation and scale) values (aka relative transform values) after moving a gameobject under a parent gameobject? The formula will be used to calculate the new relative position and rotation values so that I can move the GB to the world coordinates I want the object to be.

Scenerio

Original gameobject Transform values (not under any parent GB)

Position

x : 100
y : 20
z: 50

Rotation

x: 0.15
y: 0.2
z: 2

Scale

x: 20
y: 5
z: 10

Parent gameobject

Position

x : 25
y: 10
z: 100

Rotation

x : 0.8
y: 0.1
z: 0.3

Scale

x: 10
y: 20
z: 5

What will be the new gameobject relative (to parent) transform values when moved to world coordinates

Position

x: 120
y: 50
z: 100

Rotation

x: 0.25
y: 0.75
z: 0.30

Thank you!

1 Like

Transform.worldToLocalMatrix:

This is a transform matrix that can transform from world (global position/rotation/scale) to local space of said Transform.

Matrix4x4 has a few different methods on it to transform points, directions, rotations, etc:

[edit]
weird, I’m noticing it doesn’t have a rotation transform method… that’s stupid.

In this case, you can just take the inverse of the world rotation of the parent, and multiply the child’s world rotation by it.

localRot = Quaternion.Inverse(theTargetParent.transform.rotation) * theTargetChild.transform.rotation);
1 Like

Thank you !

2 Likes

Hi, how can I apply a matrix4x4 to my gameibject?

The Matrix4x4 has scale and rotation properties on it:
https://docs.unity3d.com/ScriptReference/Matrix4x4.html

So you can just set those on your Transform.

As for position, well there isn’t a specific property for it (for some reason), but it’s just last column of the matrix. So you can just read it out. I have methods for this here:
https://github.com/lordofduct/spacepuppy-unity-framework-3.0/blob/master/SpacepuppyUnityFramework/Utils/TransformUtil.cs#L51

What I’m wondering though is why? What are you specifically using Matrix4x4 for that you need to set Transform’s by it?

1 Like

Because the hierarchical relationship needs to be set in the thread, but transfrom can only be in the ui thread. I read this framework, and the Trans class is very well written, but it is a pity that the parent of Trans cannot be set. Otherwise this would be a perfect solution to simulate the transform hierarchy, which can be used in the thread and then create the gameobject in the ui thread

6741043--776845--upload_2021-1-19_19-3-0.png