I can't for the life of me figure out how to use a perspective projection matrix. My understanding is that, once objects are in view space, the the perspective transform uses the z-coordinate to scale the x and y coordinates.
Here's the code I'm using (C#, dotnet 7).
var viewToScreen = Matrix4x4.CreatePerspectiveFieldOfView((float)(Math.Tau / 4), 1.0f, 0.1f, 100f);
var square1 = new Vector3[]
{
new(+1, +1, 1),
new(-1, +1, 1),
new(+1, +1, 1),
new(+1, -1, 1),
};
var square2 = Array.ConvertAll(square1, v =>
{
v.Z += 3;
return v;
}).Dump("Square 2 (World Space)");
var screen1m1 = Array.ConvertAll(square1, v => Vector3.Transform(v, viewToScreen));
var screen2m1 = Array.ConvertAll(square2, v => Vector3.Transform(v, viewToScreen))
However, after the transform, the X and Y coordinates remain unchanged. Only the Z coordinate is changed, and then only slightly. This is consistent with an orthogonal projection, not a perspective projection.
What am I doing wrong here?
v.Z +=3
part... but projection matrices only work with 4D vectors. After multiplication the result vector needs to be divided by its 4thw
component. so:Vector4D result = projectionMatrix * viewMatric * position4D
where the 4th component ofposition4D
should be1
. At the end you need to calculate: $result = result / result.w$ $\endgroup$