Matrix.RotateAt in Unity3d

Viewed 472

I've been trying to create a rotation matrix around a specified center in Unity3d, but the Matrix4x4 class doesn't provide any functions that allows me to do so, even though C# does provide a function called:

public void RotateAt(double angle, double centerX, double centerY);

Which is located in System.Windows.Media namespace but inaccessible in Unity3d, is there any way I can create the same rotation matrix in Unity3d? Thank you.

1 Answers

Creating a rotation matrix around a point can be done following these steps:

  • Tranlate that matrix to the point where you want it to rotate around.
  • Rotate the matrix.
  • Translate the matrix back to the origin.

This roughly translates to:

// Set the following variables according to your setup
Vector3 centerOfRotation = ...;
float angleOfRotation = ...;
Vector3 rotationAxis = ...;

// This should calculate the resulting matrix, as described in the answer
Matrix4x4 translationToCenterPoint = Matrix4x4.Translate(centerOfRotation);
Matrix4x4 rotation = Matrix4x4.Rotate(Quaternion.AngleAxis(angleOfRotation, rotationAxis));
Matrix4x4 translationBackToOrigin = Matrix4x4.Translate(-centerOfRotation);

Matrix4x4 resultMatrix = translationToCenterPoint * rotation * translationBackToOrigin;
Related