We are trying to align our camera in order to see as closest as possible a rectangle(a face of a parallelepiped since we are in 3D). The aspect ratio of the viewport considered here and the rectangle to align do not match.
What we do:
In our scene is this rectangle. The camera is position in front of it. Here is the configuration of the camera:
projection = Matrix.CreatePerspectiveFieldOfView(
Fov, AspectRatio, NearPlane, FarPlane
);
view = Matrix.CreateLookAt(Position, Target, this.Up);
float Fov = PI/4;
float AspectRatio = device.Viewport.AspectRatio;
Vector3 Target
is set to the center of the rectangle.
Vector3 Position
is the value we are looking for.
And then to initialize the camera: oat width = (float)GraphicsDevice.Viewport.Width; float height = (float)GraphicsDevice.Viewport.Height;
float dist = (width / 2) + (height / 2);
float alpha = 0;
float beta = 0;
float gamma = 0;
alpha = (float)Math.Sqrt(Math.Pow(width / 2, 2) + Math.Pow(height / 2, 2));
beta = height / ((float)Math.Cos(MathHelper.ToRadians(70.3f)) * 2);
gamma = (float)Math.Sqrt(beta * beta - alpha * alpha);
position = new Vector3(width / 2, -height / 2, gamma);
target = new Vector3(width / 2, -height / 2, dist / 2);
camera = new Camera(GraphicsDevice.Viewport)
{
Position = position,
Target = target,
Near = 1f,
Far = 10000f
};
(VS solution)
One more precision: to create the view, we are using Matrix.CreateLookAt
and for the projection Matrix.CreatePerspectiveFieldOfView
. We are not sure if these are the perfect choices either but sounds like it.
What we get:
After some basic trigonometry we got a camera Position which works when the Height > Width. As:
But it does not when the Width > Height:
Do you...
...have any idea what are we doing wrong? Do you have any other or better way to achieve this?