Skip to content

Instantly share code, notes, and snippets.

@Santarh
Last active November 29, 2019 20:23
Show Gist options
  • Save Santarh/8709a20798d91b7a9a4dca15d13ff600 to your computer and use it in GitHub Desktop.
Save Santarh/8709a20798d91b7a9a4dca15d13ff600 to your computer and use it in GitHub Desktop.
Get 35mm Focal Length in Unity
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