[Solved] Computing camera position from view width

Problems building or running the engine, queries about how to use features etc.
Post Reply
User avatar
MadWatch
Halfling
Posts: 64
Joined: Sat Jul 06, 2013 11:25 am
x 4

[Solved] Computing camera position from view width

Post by MadWatch »

Hello everyone.

So I have a camera facing toward -Z with perspective and I want to compute its position so I get a specific view width at Z = 0. In other words, I want to compute the camera position so it shows a given length of my scene.

For now this is what I made:

Code: Select all

// viewWidth is the view width I want at Z = 0
// I compute the camera Z position to get it
Float aspectRatio = mCamera->getAspectRatio();
Float viewHeight = viewWidth / aspectRatio;
Vector3 position(0., 0., 0.);
position.z = viewHeight / tan(mCamera->getFOVy().valueRadians());
mCameraNode->setPosition(position);
This isn't perfect. The view width I get is always smaller than what I want (meaning it shows less of the world) by a factor of approximately 0.825. That mean if I set viewWidth = 20. I will actually see a view width of 16.5 in my window. This factor doesn't seem to be related to the window size or the aspect ratio. It's constant.

I don't understand where this difference comes from. Is my formula wrong ? Is there another factor I must take into account ?

Thank you for your help.
Last edited by MadWatch on Sun Jul 20, 2014 9:20 am, edited 1 time in total.
User avatar
Kojack
OGRE Moderator
OGRE Moderator
Posts: 7157
Joined: Sun Jan 25, 2004 7:35 am
Location: Brisbane, Australia
x 534

Re: Computing camera position from view width

Post by Kojack »

Try changing it to:

Code: Select all

position.z = viewHeight / tan(mCamera->getFOVy().valueRadians()*0.5f);
The getFOVy() call returns the full vertical fov range, not from the centre which is what the tan wants.
User avatar
MadWatch
Halfling
Posts: 64
Joined: Sat Jul 06, 2013 11:25 am
x 4

Re: Computing camera position from view width

Post by MadWatch »

Thank you very much :D

Now the correct formula is

Code: Select all

position.z = (viewHeight / 2.) / tan(mCamera->getFOVy().valueRadians() / 2.);
User avatar
Kojack
OGRE Moderator
OGRE Moderator
Posts: 7157
Joined: Sun Jan 25, 2004 7:35 am
Location: Brisbane, Australia
x 534

Re: [Solved] Computing camera position from view width

Post by Kojack »

Oops, yep, the height divided by 2 as well. :)
Post Reply