Getting a Visual Element's WorldPosition

Hello,

I am trying to match a gameobject’s position to a visual element’s location. I found another post from 2 years ago attempting to do a similar process. Despite following along with their code I am not finding success and I am unsure where to continue looking for answers.

image

The red dot is the target location.

Hello! Try taking a look at the UIToolkit sample project Dragon Crashers which positions a ParticleSystem in 3D space based on the position of a VisualElement.

I checked the Dragon Crashers but in the end I decided to dig myself into how to do it.

Premise: I’m currently using a reference resolution for my UI Toolkit Panel Settings

I started looking at what are the differences between my screen resolution and the ui toolkit, currently I was at a resolution of 3840x2160 in game view but my panel setting was 1920x1080 and we know UI Tookit has inverted Y:

With all these things clear I wrote this code:
1.Getting the visual element position on ui toolkit space.
2.Inverting the Y.
3.Find out the ratio of the resolutions.
4.Scale the inverted position.
5.Then find out the ScreenToWorldPoint.

Vector2 elementScreenPos = _inventoryBagButton.worldBound.center;
    
Vector3 elementScreenPosInverted = new Vector3(elementScreenPos.x, uiDocument.panelSettings.referenceResolution.y - elementScreenPos.y, 0);
    
var ratioX = Screen.width / uiDocument.panelSettings.referenceResolution.x;
var ratioY = Screen.height / uiDocument.panelSettings.referenceResolution.y;

elementScreenPosInverted = new Vector3(ratioX * elementScreenPosInverted.x, ratioY * elementScreenPosInverted.y,0);

return _mainCamera.ScreenToWorldPoint(elementScreenPosInverted);