Advertisement
DanjelRicci

GUI3DCameraFitter

Jan 15th, 2018
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.46 KB | None | 0 0
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using System.Collections;
  4.  
  5. [ExecuteInEditMode]
  6.  
  7. public class GUI3DCameraFitter : MonoBehaviour {
  8.  
  9.     public RectTransform targetRectTransform;   // Target RectTransform for size
  10.     public Camera originCamera;                 // Camera that renders the whole UI
  11.     public Camera targetCamera;                 // Camera to overlay over the RectTransform
  12.  
  13.     void Update () {
  14.  
  15.         // All the items are required for this script to work
  16.         if (!targetRectTransform || !originCamera || !targetCamera)
  17.             return;
  18.  
  19.         Vector3[] corners = new Vector3[4];
  20.         targetRectTransform.GetWorldCorners(corners);
  21.  
  22.         // Corner reading is in this order:
  23.         //
  24.         //  1 ------- 2
  25.         //  |    +    |
  26.         //  0 ------- 3
  27.         // SX: left | DX: right. Sorry, this wasn't in english before!
  28.  
  29.         Vector3 downSX = originCamera.WorldToScreenPoint(new Vector3(corners[0].x,corners[0].y,0));
  30.         Vector3 upSX = originCamera.WorldToScreenPoint(new Vector3(corners[1].x,corners[1].y,0));
  31.         Vector3 upDX = originCamera.WorldToScreenPoint(new Vector3(corners[2].x,corners[2].y,0));
  32.         Vector3 downDX = originCamera.WorldToScreenPoint(new Vector3(corners[3].x,corners[3].y,0));
  33.  
  34.         Rect finalRect = new Rect();
  35.         finalRect.x = downSX.x/Screen.width;
  36.         finalRect.y = downSX.y/Screen.height;
  37.         finalRect.width = (upDX.x - upSX.x)/Screen.width;
  38.         finalRect.height = (upDX.y - downDX.y)/Screen.height;
  39.         targetCamera.rect = finalRect;
  40.  
  41.         targetCamera.orthographicSize = (corners[2].y - corners[3].y) /2f;
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement