🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Programmatically placing a 3D object within the bounds of the camera view

Started by
3 comments, last by Juliean 4 years, 6 months ago

Given a 3D mesh, and a camera in the 3D space, how do I position the 3D mesh to be within the BoundingFrustum of the camera? That is, how do I calculate the distance of the camera to be set in such a way that the object always fits on screen regardless of the resolution.

The "hack-ish" way I have this setup right now is a constant for the distance of the camera when the aspect ratio is 1 (resolution width == height), and then multiply this constant by the aspect ratio of the device. But this method is only good if you know what the object is going to be from the start and already measured its distance from the target camera.

Advertisement

This code is from my algorithm for fitting the camera around an object (as part of an asset-preview function)

// vMin/vMax are the corners of the objects AABBs
const auto vCenter = (vMin + vMax) / 2.0f;

const auto fovy = m_camera.GetFovY();
const auto size = std::max(vMin.Length(), vMax.Length());

const auto s = size * 2.0f;
const auto distance = (s / 2.0f) / tan(fovy / 2.0f); // object distance from camera




Not sure if its 100% precise, I'm using a fixed 45° viewing angle, but it should at least give you an idea of where to start.
Juliean said:

This code is from my algorithm for fitting the camera around an object (as part of an asset-preview function)

// vMin/vMax are the corners of the objects AABBs
const auto vCenter = (vMin + vMax) / 2.0f;

const auto fovy = m_camera.GetFovY();
const auto size = std::max(vMin.Length(), vMax.Length());

const auto s = size * 2.0f;
const auto distance = (s / 2.0f) / tan(fovy / 2.0f); // object distance from camera




Not sure if its 100% precise, I'm using a fixed 45° viewing angle, but it should at least give you an idea of where to start.

The only "camera variable" in your code appears to be m_camera.GetFovY(). What exactly is that in your framework/code?

FovY Is the "Field of view in the y direction, in radians.". Its what you use to calculate the perspective projection https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3dxmatrixperspectivefovlh

It seems I didn't use the aspect ration, as my camera in this scenario is quadratic. Not sure how much difference this would make, you could try to multiple the distance with your aspect ration and maybe that would be enough.

This topic is closed to new replies.

Advertisement