Search Unity

Question How can I move a VisualElement to the position of the mouse?

Discussion in 'UI Toolkit' started by ABB13, Oct 25, 2021.

  1. ABB13

    ABB13

    Joined:
    Apr 23, 2018
    Posts:
    82
    Hi everyone, I'm trying to move a window to the position of the mouse.

    This is what I write until now but it doesn't work:
    Code (CSharp):
    1. Vector2 pos = Input.mousePosition;
    2. pos = _window.WorldToLocal(pos);
    3. _window.transform.position = pos;
     
    Last edited: Oct 26, 2021
  2. ABB13

    ABB13

    Joined:
    Apr 23, 2018
    Posts:
    82
    no one can help me?
     
  3. billykater

    billykater

    Joined:
    Mar 12, 2011
    Posts:
    329
    What you got there seems to be somewhat on the right path but a little bit mistaken.
    Imagine your Window being at (5/5) and the mouse at (7/10). Your code then transforms the position into local space giving you (2/5). That is obviously the wrong position for the window.
    In your case you will need to transform the mouseposition into local space of the window's parent (if any) and use that as the new windows position. e.g. window.parent is at (3/3) you transform your mouse position into local space (4/7) and set the window position to that giving you the desired (7/10).
    You might need to play with the position uss attribute depending on how the hierarchy is set up.
     
    ABB13 likes this.
  4. magnetic_scho

    magnetic_scho

    Joined:
    Feb 2, 2020
    Posts:
    97
    I use the following method to position my tooltip:
    Code (CSharp):
    1.  
    2. private Vector2 ScreenToPanel(Vector3 mousePosition)
    3. {
    4.     return UnityEngine.UIElements.RuntimePanelUtils.ScreenToPanel(Tooltip.panel,
    5.         new Vector2(mousePosition.x, Screen.height - mousePosition.y));
    6. }
    7.  
     
    ABB13 likes this.
  5. ABB13

    ABB13

    Joined:
    Apr 23, 2018
    Posts:
    82
    Thank you guy billykater, at the end I find this solution:

    Code (CSharp):
    1.         Vector2 pos = Input.mousePosition;
    2.         pos.y = Screen.height - (pos.y + _bar.layout.center.y);
    3.         pos.x = pos.x - _bar.layout.center.x;
    4.         _window.transform.position = pos;
    Wow magnetic_scho! your solution is much better than mine, I will try it! thank you very much