Home > front end >  How do you get relative mouse position inside a VisualElement with new Unity UI Toolkit?
How do you get relative mouse position inside a VisualElement with new Unity UI Toolkit?

Time:02-07

I'm switching over to the new UI-Toolkit (which is css-based). Using the old "canvas" and component-based ui system, I would first see if the mouse was within a ui element with a script attached to that specific ui gameobject with two functions:

public void OnPointerEnter(PointerEventData eventData)
{
    mouseInScreen = true;
}
public void OnPointerExit(PointerEventData eventData)
{
    mouseInScreen = false;
}

Then I would simply call if(OnPointerEnter.mouseInScreen == true) to find out if the mouse is in.

Unfortunately, the new UI uses one gameobject for the entire ui elements, so I'm not sure how to do this. Also, I would need to know the relative position within a UI VisualElement. (ex. mouse is 80px from left, 130px from top of t his specific element).

This new toolkit is amazing, but very new. So it is very hard to find information on it so far.

Thanks.

Edit:

I found a solution to one of the issues I had (how to determine if mouse is over a specific element.)

I used PointerDownEvent since I also need to know when the user clicks in it, but PointerEnterEvent works great for my original question.

myUIelement.RegisterCallback<PointerDownEvent>(OnPointerDownEvent, TrickleDown.TrickleDown);

Then I do what I need in this method

private void OnPointerDownEvent(PointerDownEvent evt)
{ ... }

All I need to figure out is how to get the position of the "pointer" within that ui Element now. There is a property for OnPointerDownEvent called "localPosition", but I'm not sure how to use it exactly.

CodePudding user response:

Here's my own answer after a little help in the comments and doing some research.

First get the element like so:

VisualElement rootUI = GetComponent<UIDocument>().rootVisualElement;
myUIelement = rootUI.Q<VisualElement>("ElementNameInUIBuilder");

Call this in start:

myUIelement.RegisterCallback<PointerDownEvent>(OnPointerDownEvent, TrickleDown.TrickleDown);

Then create a function:

private void OnPointerDownEvent(PointerDownEvent evt)

{ ... }

And in this function just use "evt.localPosition" to get the local coordinates within the ui element.

  •  Tags:  
  • Related