CameraExtensions.cs 621 B

12345678910111213141516171819202122
  1. using System;
  2. using UnityEngine;
  3. namespace TriLib
  4. {
  5. public static class CameraExtensions
  6. {
  7. public static void FitToBounds(this Camera camera, Transform transform, float distance)
  8. {
  9. Bounds bounds = transform.EncapsulateBounds();
  10. float magnitude = bounds.extents.magnitude;
  11. float num = magnitude / (2f * Mathf.Tan(0.5f * camera.fieldOfView * 0.017453292f)) * distance;
  12. if (float.IsNaN(num))
  13. {
  14. return;
  15. }
  16. camera.farClipPlane = num * 2f;
  17. camera.transform.position = new Vector3(bounds.center.x, bounds.center.y, bounds.center.z + num);
  18. camera.transform.LookAt(bounds.center);
  19. }
  20. }
  21. }