I've been working on some steering behaviors and ran into trouble with my logic for converting points in world space into points in local space. I had this (it's not optimized for multiple points yet, but that is not the point of my question):
public Vector2 WorldPointToLocal(Vector2 point)
{
var tx = -Vector2.Dot(this.Location, this.Heading);
var ty = -Vector2.Dot(this.Location, this.HeadingPerpendicular);
var rotationMatrix = new Matrix
{
M11 = this.Heading.X,
M12 = this.HeadingPerpendicular.X,
M21 = this.Heading.Y,
M22 = this.HeadingPerpendicular.Y,
M31 = tx,
M32 = ty
};
return Vector2.Transform(point, rotationMatrix);
}
This did not work. The returned point was always well outside the expected range. I had collated most of the mathematics from various sources and began to suspect that Vector2.Transform
wasn't doing what I thought it was supposed to do. I found an alternative implementation in C and translated it into C#:
private Vector2 VectorTransform(Vector2 vector, Matrix matrix)
{
var tempX = (matrix.M11 * vector.X) + (matrix.M21 * vector.Y) + matrix.M31;
var tempY = (matrix.M12 * vector.X) + (matrix.M22 * vector.Y) + matrix.M32;
return new Vector2(tempX, tempY);
}
When I used this implementation instead of Vector2.Transform
, everything worked perfectly.
However, I don't want to leave it at that. I'd like to understand why Vector2.Transform
does not do the same thing, and whether there's anything I can do to leverage it instead of writing my own. The API documentation doesn't help at all and I'm a bit clueless when it comes to matrix mathematics.