Search Unity

Question Switch between Orthographic and Perspective camera: How do I calculate FOV?

Discussion in '2D' started by sandbok, Jun 6, 2023.

  1. sandbok

    sandbok

    Joined:
    Dec 1, 2016
    Posts:
    19
    There's a great thread with a solution for changing a Camera between Perspective and Orthographic modes:

    https://forum.unity.com/threads/smo...ve-and-orthographic-modes.32765/#post-3431739

    This works perfectly for my game project. However, I have one problem: I need to enter the FOV manually, and while I can get it close, it's never a perfect match. Switching between orthographic and perspective results in the perspective camera being slightly zoomed in or out.

    It's hard to see in screenshots, but here's the difference:

    Ortho:
    upload_2023-6-6_12-47-11.png
    Perspective: (slightly zoomed out)
    upload_2023-6-6_12-47-18.png

    From what I've read, if the FOV doesn't change, I should be able to calculate it instead of entering it manually.

    My game is primarily 2D, and the 2D world is 20 units away from the Camera.
    The Camera's Orthographic Size is 5.
    The best FOV value I've found is 28.3.

    Here's what I've tried:

    According to this post, size / distance = tan(fov). So 5/20 = tan(fov) becomes 0.25 = tan(fov). When I try using Mathf.Atan, and convert from radians to degrees, I get a result of 14.03624347, which is way off.

    What's the correct way of calculating the FOV?
     
  2. karliss_coldwild

    karliss_coldwild

    Joined:
    Oct 1, 2020
    Posts:
    602
    Camera orthographic size is half height of the visible region. So if orthosize is 5, height of visible area is 10 units. That seems to match with your screenshot assuming dimensions of your tiles is 1 unit.
    upload_2023-6-6_8-53-25.png
    So a more complete formula is 2*atan(orthosize/distance). Which would give 28.07 degree vertical FOV which is much closer to your manually adjusted value. Multiplying the angle by 2 after atan instead of orthosize, because camera axis is typically in the middle so you get 2 right handed triangles insead of single bigger one. But if your camera main axis isn't in the middle (you probably aren't using it, but Cinemachine probably supports that) you need a more complicated calculations.
     
    sandbok likes this.
  3. sandbok

    sandbok

    Joined:
    Dec 1, 2016
    Posts:
    19
    I'm shocked that this worked, but it's perfect!

    Code (CSharp):
    1. float f = Mathf.Rad2Deg * (2 * Mathf.Atan(m_camera.orthographicSize / (distance)));
    Earlier I did try halving the orthographic size, but that still gave me wonky results. Doubling the Atan as you suggested does work, though. Thank you so much!