DEV Community

Mayank Koli
Mayank Koli

Posted on

Here’s how to use matrices for movement in Unity.

Unity lets user create a 4x4 matrix which can be used to create a translation, rotation and a scale matrix.

Multiplying all this you’ll get yourself a transformation matrix.
`// Translation matrix
Matrix4x4 translationMatrix = Matrix4x4.Translate(new Vector3(2f, 0f, 0f));

    // Rotation matrix (45 degrees around the Y-axis)
    Matrix4x4 rotationMatrix = Matrix4x4.Rotate(Quaternion.Euler(0f, 0f, 0f));

    // Scaling matrix
    Matrix4x4 scalingMatrix = Matrix4x4.Scale(new Vector3(1f, 1f, 1f));

    // Combine the transformation matrices
    Matrix4x4 transformationMatrix = translationMatrix * rotationMatrix * scalingMatrix;`
Enter fullscreen mode Exit fullscreen mode

Here I showed you how to create transformation matrix. Now lets do some operations on it

transform.position = transformationMatrix.MultiplyPoint(transform.position);
transform.rotation = rotationMatrix.rotation * transform.rotation;
transform.localScale = transformationMatrix.MultiplyVector(new Vector3( 1, 2, 3));
Enter fullscreen mode Exit fullscreen mode

To test this put all this code in a script and stick it to a cube.

Also unity only lets you create a 4x4 matrix but here’s how you can create a 3x3 matrix.

public class Matrix3x3{
  public float[,] matrix;
  public Matrix3x3(Matrix4x4 matrix4x4){
    matrix = new float[3,3];
    for(int i=0;i<3;i++){
      for(int j=0;j<3;j++){
        matrix[i,j] = matrix4x4[i,j];
}}}}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)