Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.UI;
- using System.Collections;
- [ExecuteInEditMode]
- public class GUI3DCameraFitter : MonoBehaviour {
- public RectTransform targetRectTransform; // Target RectTransform for size
- public Camera originCamera; // Camera that renders the whole UI
- public Camera targetCamera; // Camera to overlay over the RectTransform
- void Update () {
- // All the items are required for this script to work
- if (!targetRectTransform || !originCamera || !targetCamera)
- return;
- Vector3[] corners = new Vector3[4];
- targetRectTransform.GetWorldCorners(corners);
- // Corner reading is in this order:
- //
- // 1 ------- 2
- // | + |
- // 0 ------- 3
- // SX: left | DX: right. Sorry, this wasn't in english before!
- Vector3 downSX = originCamera.WorldToScreenPoint(new Vector3(corners[0].x,corners[0].y,0));
- Vector3 upSX = originCamera.WorldToScreenPoint(new Vector3(corners[1].x,corners[1].y,0));
- Vector3 upDX = originCamera.WorldToScreenPoint(new Vector3(corners[2].x,corners[2].y,0));
- Vector3 downDX = originCamera.WorldToScreenPoint(new Vector3(corners[3].x,corners[3].y,0));
- Rect finalRect = new Rect();
- finalRect.x = downSX.x/Screen.width;
- finalRect.y = downSX.y/Screen.height;
- finalRect.width = (upDX.x - upSX.x)/Screen.width;
- finalRect.height = (upDX.y - downDX.y)/Screen.height;
- targetCamera.rect = finalRect;
- targetCamera.orthographicSize = (corners[2].y - corners[3].y) /2f;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement