Last active
November 29, 2019 20:23
-
-
Save Santarh/8709a20798d91b7a9a4dca15d13ff600 to your computer and use it in GitHub Desktop.
Get 35mm Focal Length in Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
namespace Utils | |
{ | |
public static class CameraExtensions | |
{ | |
private static readonly float HalfDiagonalOf35Millimeter = Mathf.Sqrt(36 * 36 + 24 * 24) * 0.5f; | |
public static float Get35MillimeterFocalLength(this Camera camera) | |
{ | |
if (camera == null) return 0; | |
// camera.fieldOfView is vertical field of view. | |
// But meanings changes depending on whether camera.usePhyiscalProperties flag is enabled. | |
// if enabled, camera.fieldOfView is cropped camera.sensorSize's vertical fov. | |
// if disabled, camera.fieldOfView is entire screen's vertical fov. | |
var sensor = camera.usePhysicalProperties ? camera.sensorSize : new Vector2(camera.aspect, 1); | |
var sensorDiag = Mathf.Sqrt(sensor.x * sensor.x + sensor.y * sensor.y); | |
var verticalFov = camera.fieldOfView * Mathf.Deg2Rad; | |
var camToSensor = sensor.y / Mathf.Tan(verticalFov * 0.5f); | |
// tan(theta) = 35mmDiag / focalLength = sensorDiag / camToSensor | |
// so, focalLength = 35mmDiag * camToSensor / sensorDiag | |
return HalfDiagonalOf35Millimeter * camToSensor / sensorDiag; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment