How to Implement Transform Logic in unity

Viewed 27

I want to simulate the Transform operation in the thread, such as setting the parent node for it. What I can think of is to create a virtual Transform, and then record the localposition, localrotation, and localscale. But when I set the parent node for virtual transform, how do I update localposition, localrotation, and localscale? What is the conversion relationship between localposition and position, localrotation and rotation, localscale and scale?

1 Answers

This is a general matrix mathematics problem, in Unity you can use Matrix4x4. It is a struct and can be used completely independent from the Unity main thread.

Each virtual node can be a simple matrix created by Matrix4x4.TRS. Using Matrix4x4.SetTRS to change these values.

Matrix4x4.TRS(localPosition, localRotation, localScale);

In a nutshell if you have a parent node and a child node, to transform a vector from child's local space to world, you can call Matrix4x4.MultiplyPoint on each matrix from child's to parent's.

v = childMatrix.MultiplyPoint(v);
v = parentMatrix.MultiplyPoint(v);

The above process can be merged into a single matrix. You can cache it for efficiency.

childToWorldMatrix = parentMatrix * childMatrix;
v = childToWorldMatrix.MultiplyPoint(v);

The opposite operation (from world to local) only needs to call the same method on Matrix4x4.inverse from the reverse order.

v = parentMatrix.inverse.MultiplyPoint(v);
v = childMatrix.inverse.MultiplyPoint(v);
Related