TRS Matricies - Gr8-Tools/game-developer-roadmap-doc GitHub Wiki
TRS Matrices in Unity
Total time: 5 hours
Key Definitions and Formulas
Translation Matrix - A matrix that translates (moves) an object in 3D space. It has the form:
[1 0 0 x]
[0 1 0 y]
[0 0 1 z]
[0 0 0 1]
Where x, y, z are the translation amounts in the x, y, z axes respectively.
Rotation Matrix - A matrix that rotates an object around one or more axes in 3D space. The basic rotation matrices are:
Rotation around X axis:
[1 0 0 0]
[0 cosθ -sinθ 0]
[0 sinθ cosθ 0]
[0 0 0 1]
Rotation around Y axis:
[ cosθ 0 sinθ 0]
[ 0 1 0 0]
[-sinθ 0 cosθ 0]
[ 0 0 0 1]
Rotation around Z axis:
[cosθ -sinθ 0 0]
[sinθ cosθ 0 0]
[ 0 0 1 0]
[ 0 0 0 1]
Where θ is the angle of rotation in radians. Rotations can be combined by multiplying the matrices.
To receive final rotation matrix you should multiply them in correct order. In case of these matrices it's
Rz * Ry * Rx
. WARNING: In the video from the following sources the implementation differs from current so the author used another matricies.
Scale Matrix - A matrix that scales (changes the size of) an object in 3D space. It has the form:
[sx 0 0 0]
[ 0 sy 0 0]
[ 0 0 sz 0]
[ 0 0 0 1]
Where sx, sy, sz are the scale factors along each axis.
Transformation Matrix - A single matrix that represents the combination of translation, rotation, and scaling. It is calculated by multiplying the individual T, R, S matrices together in that order.
Algorithms
Calculating a Transformation Matrix
- Initialize an identity matrix as the transformation matrix
- Multiply the translation matrix T onto the transformation matrix
- Multiply the rotation matrix R onto the transformation matrix
- Multiply the scale matrix S onto the transformation matrix
- The final transformation matrix represents the combination of all transformations
For example, to rotate 45 degrees around Y, scale by 2, and translate by (1,2,3):
- Tform = identity
- Tform = Tform * TranslationMatrix(1,2,3)
- Tform = Tform * RotationMatrixY(45)
- Tform = Tform * ScaleMatrix(2,2,2)
- Tform is the final transformation matrix
Applying a Transformation in Unity
- Create a GameObject to represent the object to transform
- Get the transformation matrix as a Matrix4x4 from the calculations
- Set the transform.localMatrix of the GameObject to the matrix
- The GameObject will now be in its transformed position, rotation, and scale
Videos for Further Study
Time: 20 minutes
Time : 40 minutes
Sources
Practice Tasks
MathLib
- Create your own implementation of TRS-matrix: provide
position
,rotation
andscale
vectors and combine them inside one Matrix. It's supposed to create your won implementation ofMatrix4x4
to write by your hands multiplication operations.
Time: 3 hours
Compare the results with unity-defined TRS-matrix. If the results are differ the most possible case is incorrect order of multiplications.
- Create your own method to apply your TRS-Matrix operations to a Vector3(D) point.
Time: 1 hour