Reputation: 303
In Unity, is there a way to detect in the camera's field of view, if a cube object is infront of a text component which is in World Space? Such that the cube blocks the text in camera's FoV?
Upvotes: 1
Views: 65
Reputation: 323
//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;
It helped me in the past and i hope it will help you too
font: https://answers.unity.com/questions/799616/unity-46-beta-19-how-to-convert-from-world-space-t.html
Upvotes: 1