Influence-Engine / Influence

Influence Engine - 2D and 3D game engine
MIT License
2 stars 1 forks source link

Incorrect Order of Matrix Multiplications in Transformations #4

Open leAdmin666 opened 1 month ago

leAdmin666 commented 1 month ago

Background

In 3D graphics, transforming objects involves applying a series of operations: scaling, rotation, and translation. These operations are represented by matrices and are applied in a specific order to achieve the desired transformation. The correct order of applying these transformations is crucial for ensuring that the object behaves as expected.

Problem

The current implementation of the Transform class in our project applies transformations in the order of translation, rotation, and then scaling:

void UpdateModelMatrix()
{
    Matrix4x4 scaleMatrix = Matrix4x4.CreateScale(_scale);
    Matrix4x4 rotationMatrix = _rotation.ToRotationMatrix();
    Matrix4x4 translationMatrix = Matrix4x4.CreateTranslate(_position);

    modelMatrix = translationMatrix * rotationMatrix * scaleMatrix;
}

This order can lead to incorrect transformations, where objects do not appear in the right position, orientation, or size in the 3D space.

Explanation

The correct order of transformations should be:

  1. Rotation
  2. Scaling
  3. Translation

Here's why:

  1. Rotation: When we rotate an object, we want it to rotate around its local origin. If the object has already been translated, rotating it will cause it to orbit around the origin of the world space, rather than rotating in place. Applying rotation first ensures the object rotates around its own center.

  2. Scaling: Scaling should typically occur around the object's local origin. If scaling is applied after translation, the object will scale in the direction of the translation, which can lead to undesired stretching. Scaling after rotation ensures that the object scales correctly along its local axes.

  3. Translation: Translation is the last step because it moves the object to its final position in the world space. By applying translation last, we ensure that the object is positioned correctly after it has been rotated and scaled around its local origin.

Solution

To achieve the correct transformation, the matrices should be multiplied in the following order:

void UpdateModelMatrix()
{
    Matrix4x4 scaleMatrix = Matrix4x4.CreateScale(_scale);
    Matrix4x4 rotationMatrix = _rotation.ToRotationMatrix();
    Matrix4x4 translationMatrix = Matrix4x4.CreateTranslate(_position);

    modelMatrix =  rotationMatrix * scaleMatrix * translationMatrix;
}

By making this change, we ensure that all transformations are applied correctly, resulting in the expected positioning, orientation, and scaling of objects within the 3D space.

realQuartzi commented 1 month ago

This makes absolute sense to me and I believe you are right. The logic is there and I will test this with the limited amount of testing we can do at this time :3