# How to transform a matrix's local space position into another's local space

When looking at an example to learn how to do per pixel collision, I came across this:

// Calculate a matrix which transforms from A's local space into
// world space and then into B's local space
Matrix transformAToB = transformA * Matrix.Invert(transformB);


I have a (very) basic understanding of matrices, so I'm not too sure how this works, how can you convert the local space of one matrix to another by multiplying by the others inverted?

A transformation matrix has two functions: It can move and rotate a vector. We need one vector that we transform a little. Let's call it positionRelativeToA. We can transform this vector to the global world coordinates as follows:

Vector positionAbsolute = positionRelativeToA * transformA;


Of course, we can do the same with B:

Vector positionAbsolute = positionRelativeToB * transformB;


If we want to transform from the local space of B to A, we are interested in positionRelativeToB, so we change the above equation system a little:

//positionRelativeToB * transformB = positionRelativeToA * transformA;
//multiply with Matrix.inverse(transformB) on both sides
positionRelativeToB = positionRelativeToA * transformA * Matrix.inverse(transformB);


If you have to use that operation very often it makes sense to pre-calculate the Matrix * Matrix operation:

Matrix transformAToB = transformA * Matrix.inverse(transformB);
// ...
Vector positionRelativeToB = positionRelativeToA * transformAToB;