• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
1
Question by SuperMoog · Aug 23, 2015 at 09:42 PM · canvasrecttransformcamera viewportscreen resolutioncoordinate-system

Converting Canvas Space to Screen Space

Hey all,

I am very new to Unity and my math skills aren't fantastic so I apologise in advance for the newbie question ;)

Scenario:

I have a camera in my scene and I need to adjust it's viewport as the screen resizes in order to place it correctly wit$$anonymous$$n the surrounding UI. I decided to add a container to my UI canvas so that t$$anonymous$$s can be repositioned and sized automatically by Unity. Then my plan was to simply make the cameras viewport position and size match it.

In order to ac$$anonymous$$eve t$$anonymous$$s I decided to make the below component to handle the repositioning and resizing.

I am working in 2D and therefore using an orthograp$$anonymous$$c camera, the UI is in Screen Overlay mode with a pixel perfect canvas. There is also a canvas scaler set to scale to screen size with a reference resolution of 1920x1080.

Code:

Note that I have removed contractual (null) checks from Awake to make the example more concise:

 public class ScaleCameraViewportToCanvasTarget : MonoBehaviour
 {
     // Unity visible properties
     public GameObject ScaleToFit; 
     //

     private Camera cameraToScale;
     private RectTransform targetTransform;
     private Canvas canvas;

     public void Awake()
     {
         t$$anonymous$$s.targetTransform = ScaleToFit.GetComponent<RectTransform>();
         t$$anonymous$$s.canvas = ScaleToFit.GetComponentInParent<Canvas>();
         t$$anonymous$$s.cameraToScale = GetComponent<Camera>();
     }

     public void LateUpdate()
     {
         // Determine target dimensions taking in to consideration canvas scaling
         var width = targetTransform.rect.width * canvas.scaleFactor;
         var height = targetTransform.rect.height * canvas.scaleFactor;


         // Get centre point of our target in Canvas Space
         var centreX = targetTransform.anchoredPosition.x;
         var centreY = targetTransform.anchoredPosition.y;


         // Adjust for anchor from centre to upper left
         var left = centreX - (width * 0.5f);
         var top = centreY - (height * 0.5f);


         // Convert from Canvas Space to Screen Space
         left = left + (Screen.width * 0.5f);
         top = top + (Screen.height * 0.5f);


         // Adjust camera viewport
         var targetRect = new Rect(left, top, width, height);
         t$$anonymous$$s.cameraToScale.pixelRect = targetRect;
     }
 }

Problem:

T$$anonymous$$s does kinda work but it isn't accurate. When canvas scaling is off everyt$$anonymous$$ng works as expected but when it is enabled the width and height are correct but the left, top positioning isn't correct.

For example:

X is -0.03813588 when it should be 0.0

Y is 0.04876541when it should be 0.03876541 (±)

Any ideas? I have spent a lot of time on t$$anonymous$$s and I can't help but t$$anonymous$$nk I am doing somet$$anonymous$$ng fundamentally wrong.

Many thanks in advance,

Mark

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Baste · Aug 23, 2015 at 10:29 PM 0
Share
avatar image SuperMoog · Aug 23, 2015 at 10:45 PM 0
Share

2 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by SuperMoog · Aug 24, 2015 at 08:03 AM

Hi all,

I have worked out the issue myself. I wasn't adjusting the position by the scale factor. Applying the factor to the anchored position prior to manipulation fixes the issue:

         var centreX = targetTransform.anchoredPosition.x * canvas.scaleFactor;
         var centreY = targetTransform.anchoredPosition.y * canvas.scaleFactor;

Many Thanks,

Mark

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image nhanc18 · May 17, 2021 at 02:33 PM 0
Share
avatar image
0

Answer by Malkyne · Dec 13, 2015 at 08:13 PM

For future reference, t$$anonymous$$s is the code I use to do the same t$$anonymous$$ng.

Whenever your RectTransform resizes, it's going to trigger OnRectTransformDimensionsChange. You can use t$$anonymous$$s to do your camera viewport adjustments. So, you can put t$$anonymous$$s code on your RectTransform:

 [RequireComponent(typeof(RectTransform))]
 public class CameraViewSizer : MonoBehaviour
 {
     [SerializeField]
     private Camera _camera;

     protected void OnRectTransformDimensionsChange()
     {
         _camera.pixelRect = Util.RectTransformToScreenSpace((RectTransform)t$$anonymous$$s.transform);
     }
 }


T$$anonymous$$s is the RectTransformToScreenSpace function used above:

 public static class Util
 {
     public static Rect RectTransformToScreenSpace(RectTransform transform)
     {
         Vector2 size = Vector2.Scale(transform.rect.size, transform.lossyScale);
         return new Rect((Vector2)transform.position - (size * 0.5f), size);
     }
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

27 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Moved GameObject under Canvas (Parent), transform.position vector coordinates mismatch 0 Answers

How to detect if a scrollrect is close to reach its bottom? 0 Answers

Cell size to Canvas size 1 Answer

UI Canvas Anchor points are stuck in the bottom left corner and disabled when in overlay mode. 1 Answer

How to tell if a RectTransform is within the visible area of a ScrollRect 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges