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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Resolved How to position VisualElement at specific screen coordinates?

Discussion in 'UI Toolkit' started by Codalyn, May 19, 2022.

  1. Codalyn

    Codalyn

    Joined:
    Dec 30, 2014
    Posts:
    41
    I need to place a particular visual element at specific screen coordinates. For example, say I want a visual element that attaches to the cursor position... how would I do that? Is there a standardized function that translates from screen coordinates to "ui toolkit canvas coordinates"?
     
  2. Midiphony-panda

    Midiphony-panda

    Joined:
    Feb 10, 2020
    Posts:
    235
    Take a look at
    RuntimePanelUtils
    :)
    In particular, you could use :
    public static Vector2 RuntimePanelUtils.ScreenToPanel(IPanel panel, Vector2 screenPosition)


    However the position you will get is in (world) panel space, not your VisualElement local space.
    So you might need to
    visualElement.WorldToLocal(whatever)
     
    VoodooDetective likes this.
  3. Codalyn

    Codalyn

    Joined:
    Dec 30, 2014
    Posts:
    41
    Thanks!

    Had to dig around a bit to find out what a panel is and where to get it from (visualElement.panel). They should've just made a VisualTreeUtils class, since you are always dealing with VisualElement in UIToolkit code...
     
  4. gnovos

    gnovos

    Joined:
    Apr 29, 2020
    Posts:
    23
    This works for me, but the y-axis is reversed. I can compensate with Screen.height - pos.y, but I'd prefer to understand why it's happening. If anyone has a clue what's causing this, please fill me in.