Positioning with anchoredPosition

Hi,

How do I position a UI object according to an object in world space?

E.g. Have a UI arrow on top of a character in world space and say click this

Do I use viewport value? Or Screen point value?

Setting: Screen Space - Overlay, Reference Resolution: 800, 600

This is just a known quick fix because the limitation is that this UI object has to have the anchor preset to the bottom left to match the screen point (0,0 being in the bottom left). I’m sure you can do more math and adjust the x and y if you use another anchor preset other than bottom left. Also I have a feeling that there is some kind of function that will automagically do all this for you no matter what UI settings you are using.

Vector3 screenPos = Camera.main.WorldToScreenPoint( objectInWorldSpace.transform.position);
m_rectTransform.anchoredPosition = (Vector2)screenPos;

Thanks, I have tried this already. And somehow it is still offset a little bit.

So I forgot to mention the parent of this UI object has to also be bottom left, and it has to have a position of 0, 0, with a height and width of 0. If these values are set you have to do more math to adjust this. If you have multiple parents for this object you have to also either set the parent to bottom left, pos 0,0, and height width 0 or keep offsetting it by these values. Another thing that can be effecting this is on your canvas, there is a canvas scaler component, there is a Scale Factor which if its different than 1 you have to to do scale the newpos by this amount.

rootCanvasRect is the RectTransform of the root Canvas that has your UI object.

Vector3 screenPos = Camera.main.WorldToViewportPoint( objectInWorldSpace.transform.position);
screenPos.x *= rootCanvasRect.rect.width;
screenPos.y *= rootCanvasRect.rect.height;
transform.position = screenPos;
1 Like

Thanks,

I ended up just use an normal sprite and set the sort order very high, it is actually better this way because I would have to position the arrow if the camera moves too. Now I don’t have to deal with the camera movement.

Why aren’t you using a canvas set to “world space” render mode?

1 Like

Yea, I know this is another way. But I just wanted to find out if I can do that with Screen Space layout.