Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Camera.WorldToScreenPoint + free aspect woes

Discussion in 'UI Toolkit' started by jnhackleman_unity, Nov 16, 2021.

  1. jnhackleman_unity

    jnhackleman_unity

    Joined:
    Sep 16, 2021
    Posts:
    20
    Hi all,
    I'm trying to place some label elements over top of some game objects. This works fine when my Panel Settings Scale Mode is set to a Constant - but we want it set to "Scale With Screen Size"
    This seems to mean that the coordinates returned from

    Code (CSharp):
    1. Camera.WorldToScreenPoint(pTransform);
    Are not accurate on screen unless I am in a set resolution. See video:
    https://drive.google.com/file/d/1H2FgCDg-9QFKN_qcjoOdWYP9Kcjs9cAX/view?usp=sharing
    (Sorry about the low quality, but you still see the required info)

    I did find this thread with a solution (https://answers.unity.com/questions/672272/issue-with-worldtoscreenpoint.html)
    However this solution doesn't work in UI Toolkit because there is no canvas.
    I've also checked my UIDocument.PanelSettings.scale and it's always 1.

    Does anyone know the math, or how I can find out?

    Thanks

    EDIT: I forgot to post my PanelSettings:
    https://i.gyazo.com/b32a9573741a26bd06b589abcb7a2b9e.png
     
    Last edited: Nov 16, 2021
  2. Maverick

    Maverick

    Joined:
    Dec 18, 2009
    Posts:
    225
  3. jnhackleman_unity

    jnhackleman_unity

    Joined:
    Sep 16, 2021
    Posts:
    20
    Thanks.
    I ended up creating a helper method that I hope others will find useful:

    Code (CSharp):
    1.     public static Vector2 GetScreenPositionFromTransform(Camera pCamera, Vector3 pTransformPosition, VisualElement pRoot)
    2.     {
    3.         var worldToScreenPoint = pCamera.WorldToScreenPoint(pTransformPosition);
    4.         return RuntimePanelUtils.ScreenToPanel(pRoot.panel, new Vector2(worldToScreenPoint.x, Screen.height - worldToScreenPoint.y));
    5.     }
    It's working wonderfully -
    I think the only thing it assumes is that your root visual element is of course the entirety of the screen size, and then the ui elements that you are positioning are of course being positioned relative to the same entirety.