Skip to content

Instantly share code, notes, and snippets.

@gszauer
Created June 6, 2013 00:41
Show Gist options
  • Save gszauer/5718489 to your computer and use it in GitHub Desktop.
Save gszauer/5718489 to your computer and use it in GitHub Desktop.
void FitMeshInFrustum(float distanceFromCamera) {
currentWidth = Screen.width;
if (initialSize && (prevWidth == currentWidth)) return;
initialSize = true;
float scaleX = 1.0f, scaleY = 1.0f;
// Find mesh bounds
cachedTransform.localScale = Vector3.one;
Mesh mesh = GetComponentInChildren<MeshFilter>().mesh;
mesh.RecalculateBounds();
float meshWidth = mesh.bounds.extents.x * 2.0f;
float meshHeight = mesh.bounds.extents.y * 2.0f;
fudgeX = meshWidth * 0.25f;
// Get frustum size
float fov = CameraManager.Instance.camera.fov;
float aspect = CameraManager.Instance.camera.aspect;
float frustumHeight = 2.0f * distanceFromCamera * Mathf.Tan(fov * 0.5f * Mathf.Deg2Rad);
float frustumWidth = frustumHeight * aspect;
aspect = Screen.width / Screen.height;
if (!naturalParalax) {// If paralaxing, add extra room
frustumWidth += fudgeX + 0.25f;// * 0.5f;
frustumHeight += fudgeY + 0.25f;// * 0.5f;
}
bool horizontal = Screen.width > Screen.height;//frustumWidth > frustumHeight;
bool square = Screen.width == Screen.height;
/*if (!horizontal) {
float temp = frustumHeight;
frustumHeight = frustumWidth;
frustumWidth = frustumHeight;
}*/
if (square) { // Ideally, this will never happen
if (meshWidth == 0.0f) meshWidth = 0.001f;
scaleX = scaleY = frustumWidth / meshWidth;
} else if (horizontal) {
if (meshWidth == 0.0f) meshWidth = 0.001f;
scaleX = frustumWidth / meshWidth;
#if COMPENSATE_FOR_TOP_GEOMETRY
scaleY = scaleX * 1.5f / aspect;
#elif ARBITRARI_STRETCH_COMPENSATION
scaleY = scaleX * 1.25f / aspect;
#else
scaleY = scaleX / aspect;
#endif
} else {
if (meshHeight == 0.0f) meshHeight = 0.001f;
scaleY = frustumHeight / meshHeight;
#if COMPENSATE_FOR_TOP_GEOMETRY
//scaleY *= 1.1f;
//aspect *= 1.5f;
#elif ARBITRARI_STRETCH_COMPENSATION
scaleY *= 1.25f;
aspect *= 1.25f;
#endif
scaleX = scaleY * aspect;
}
cachedTransform.localScale = new Vector3(scaleX, scaleY, 1.0f);
/*if (!horizontal && !square) {
cachedTransform.localPosition += cachedTransform.up * -5.0f;
}*/
prevWidth = currentWidth;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment