Programming/Unity

Changes WorldPosition to CanvasPosition

Inner-Peace 2020. 10. 21. 08:13
반응형

RectTransform canvasRect = Canvas.GetComponent<RectTransform>();

 

Vector2 viewPoint = Camera.main.WorldToViewPortPoint(WorldObject.transform.position);

Vector2 canvasPoint = new Vector2( ((ViewportPosition.x*canvasRect.sizeDelta.x)-(canvasRect.sizeDelta.x*0.5f)),

                                                          ((ViewportPosition.y*canvasRect.sizeDelta.y)-(canvasRect.sizeDelta.y*0.5f)) );

 

ui.anchoredPosition = canavsPoint

 

 

---------------------------------------------------------------

//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;

 

 

출처 : answers.unity.com/questions/799616/unity-46-beta-19-how-to-convert-from-world-space-t.html

반응형