It seems to be like this:
Vector2 Convert(Vector3 pos, const Matrix& viewMatrix, const Matrix& projectionMatrix, int screenWidth, int screenHeight) { pos = Vector3::Transform(pos, viewMatrix); pos = Vector3::Transform(pos, projectionMatrix); pos.X = screenWidth*(pos.X + 1.0)/2.0; pos.Y = screenHeight * (1.0 - ((pos.Y + 1.0) / 2.0)); return Vector2(pos.X, pos.Y); }
What we are doing here is simply to convey the Vector, although there are two transformation matrices: view, and then projection. After projection, you get a vector with Y and X between -1 and 1. We do the corresponding transformation to get the real coordinates of the pixels and return a new vector2. Note that the z-component "pos" also stores the depth of a point in the screen space at the end of the function.
You need a βviewβ matrix because it determines where the camera is located and rotates. A projection only defines how the 3D space is βflattenedβ on the 2D space.
The field of view is not farZ. The projection matrix has some parameters, among which:
- field of view, FOV, that is, the horizontal angle of view, in radians;
- far plane or farZ: this determines the maximum distance that a point can be from the camera;
- nearest plane, near Z: the minimum distance that can be from the camera point.
Besides the math problem, you can directly use Vector2 instead of allocating a heap (returning a pointer). Vector2 is a lightweight structure, and pointers are likely to cause headaches in this context (where are you going to remove it, etc.). Also note that I used const links, since we do not modify them except the vector. This requires a local copy, so it is not a link at all.
source share