Last active
July 17, 2024 18:55
-
-
Save unitycoder/54f4be0324cccb649eff to your computer and use it in GitHub Desktop.
Move UI element to world gameobject position
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://forum.unity.com/threads/overlay-canvas-and-world-space-coordinates.291108/#post-9627593 | |
// translating between overlay canvas and world space coordinates | |
uiObject.transform.position = RectTransformUtility.WorldToScreenPoint(Camera.main, worldObject.transform.TransformPoint(Vector3.zero)); | |
-------- | |
// http://answers.unity3d.com/questions/799616/unity-46-beta-19-how-to-convert-from-world-space-t.html | |
//this is your object that you want to have the UI element hovering over | |
GameObject WorldObject; | |
//this is the ui element | |
RectTransform UI_Element; | |
//first you need the RectTransform component of your canvas | |
RectTransform CanvasRect=Canvas.GetComponent<RectTransform>(); | |
//then you calculate the position of the UI element | |
//0,0 for the canvas is at the center of the screen, whereas WorldToViewPortPoint treats the lower left corner as 0,0. Because of this, you need to subtract the height / width of the canvas * 0.5 to get the correct position. | |
Vector2 ViewportPosition=Cam.WorldToViewportPoint(WorldObject.transform.position); | |
Vector2 WorldObject_ScreenPosition=new Vector2( | |
((ViewportPosition.x*CanvasRect.sizeDelta.x)-(CanvasRect.sizeDelta.x*0.5f)), | |
((ViewportPosition.y*CanvasRect.sizeDelta.y)-(CanvasRect.sizeDelta.y*0.5f))); | |
//now you can set the position of the ui element | |
UI_Element.anchoredPosition=WorldObject_ScreenPosition; | |
This really helped me. Really good solution. Thank you.
Thank you very much for the solution; it was incredibly helpful.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you. Straight forward and really easy to understand.