How to muliply a quaternion with a matrix4x4?

I know that we can use matrix4x4.TRS() but I want to demonstrate about transformation order, so I use a quaternion for rotation and a translation matrix (4x4). But I do not know how to multiply it using “*” operator?

I also test to multiply a quaternion with a vector, then a translation matrix with a vector, but the result is different as testing with another tool.

Anybody help me, please?

1 Answer

1

To use a quaternion you have to convert it into a 3x3 rotation matrix. The multiply operator of a quaternion with a vector3 looks like this:

//C# (taken from UnityEngine.dll)
public static Vector3 operator *(Quaternion rotation, Vector3 point)
{
	float num = rotation.x * 2f;
	float num2 = rotation.y * 2f;
	float num3 = rotation.z * 2f;
	float num4 = rotation.x * num;
	float num5 = rotation.y * num2;
	float num6 = rotation.z * num3;
	float num7 = rotation.x * num2;
	float num8 = rotation.x * num3;
	float num9 = rotation.y * num3;
	float num10 = rotation.w * num;
	float num11 = rotation.w * num2;
	float num12 = rotation.w * num3;
	Vector3 result;
	result.x = (1f - (num5 + num6)) * point.x + (num7 - num12) * point.y + (num8 + num11) * point.z;
	result.y = (num7 + num12) * point.x + (1f - (num4 + num6)) * point.y + (num9 - num10) * point.z;
	result.z = (num8 - num11) * point.x + (num9 + num10) * point.y + (1f - (num4 + num5)) * point.z;
	return result;
}

As you can see they “kind of” generate a 3x3 matrix but without going through the Matrix4x4 class which would be wuite a bit overhead. However you can simply use this to create a Matrix4x4 out of the quaternion.

However it’s probably way easier to use

    var rotation = Matrix4x4.TRS(Vector3.zero, yourQuaternion, Vector3.one);

Finally you can decide on your own in which order you multiply the matrices together.

Why not directly multiply it with another quaternion got from Matrix4x4.rotation? Quaternion has the character that it is multipliable.