Skip to content

Instantly share code, notes, and snippets.

@forestrf
Last active December 18, 2016 19:13
Show Gist options
  • Save forestrf/e71ce91677fd48a762589dbe0deb3931 to your computer and use it in GitHub Desktop.
Save forestrf/e71ce91677fd48a762589dbe0deb3931 to your computer and use it in GitHub Desktop.
Get the minimum radius of a sphere around an Unity3D Camera that guarantees that outside of that radius nothing will intersect the camera's frustum
// Get the minimum radius sphere of a camera in which the camera crosses something. For a spherecast, for example.
public static float GetRadiusOfCamera(Camera camera) {
/*
Calculate the radius of the smallest sphere that contains perfectly the camera
The vertices of the sides of the near plane must touch the sphere and the
and also from the near plane center going backwards by camera.nearClipPlane
SIDE
_________
/ /| \
/ a/ | \sphere
/ / |c \
| / | |
|/____| |
b
FRONT
________
/ \
/___fw_____\sphere
/ |\ | \
| | \c ffh| |
| | \ | |
/|\
|
Center of the near plane frustum
b => camera.nearClipPlane
c => sqrt(frustumHeightHalf^2 + frustumWidthHalf^2)
a => radius = sqrt(b^2 + c^2)
fw => frustum width
fhh => frustumHeightHalf = frustum height / 2
*/
// http://docs.unity3d.com/Manual/FrustumSizeAtDistance.html
float b = camera.nearClipPlane;
float frustumHeightHalf = b * Mathf.Tan(camera.fieldOfView * 0.5f * Mathf.Deg2Rad);
float frustumWidthHalf = frustumHeightHalf * camera.aspect;
float c = Mathf.Sqrt(frustumHeightHalf * frustumHeightHalf + frustumWidthHalf * frustumWidthHalf);
return Mathf.Sqrt(b * b + c * c);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment