- Home /
Adjusting camera so the whole level is visible
I want to adjust my Perspective camera so the whole level is visible. (Top-Down) The level is randomly generated so I need to programmatically set the camera position I have the bounds of the level, The script I have found does work but zooms too far away when the level is big
void Start() {
GenerateLevel();
bounds = new Bounds(transform.position, Vector3.one);
Renderer[] renderers = GetComponentsInChildren<Renderer>();
foreach (Renderer renderer in renderers)
{
bounds.Encapsulate(renderer.bounds);
}
float cameraDistance = 2.0f; // Constant factor
Vector3 objectSizes = bounds.max - bounds.min;
float objectSize = Mathf.Max(objectSizes.x, objectSizes.y, objectSizes.z);
float cameraView = 8.0f * Mathf.Tan(0.5f * Mathf.Deg2Rad * cam.fieldOfView); // Visible height 1 meter in front
float distance = cameraDistance * objectSize / cameraView; // Combined wanted distance from the object
distance += 0.5f * objectSize; // Estimated offset from the center to the outside of the object
cam.transform.position = bounds.center - distance * cam.transform.forward;
}
Comment