- Home /
Rect Transform to World Position Conversion
Hi,
I'm new to unity's new UI system, Can someone please help me in my problem. I have a UI image in my 2d game containing two cameras. The UI image is shown using a camera for showing UI objects only. and the main camera is used to show game objects in World Space. The UI image should be moved to the position of another game object in World Space. I have tried several methods to move it, but it is not working cause, the conversion from rect transform of UI Image to the World space of WOrld object is not working correctly. Can someone please help me regarding the conversion from Rect transform component of UI image to World position.
Thanks in advance. Sorry to disturb you, but I had tired because of this conversion error.
Hello, I was wondering the same. Did you got a solution? thanks
Answer by Griffo · Apr 07, 2016 at 01:40 PM
// first you need the RectTransform component of your canvas
var CanvasRect : RectTransform = 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.
*/
var ViewportPosition : Vector2 = cam.WorldToViewportPoint(target.position);
// clamp the grenade to the screen boundaries
ViewportPosition.x = Mathf.Clamp01(ViewportPosition.x);
ViewportPosition.y = Mathf.Clamp01(ViewportPosition.y);
var WorldObject_ScreenPosition : Vector2 = new Vector2(((ViewportPosition.x*CanvasRect.sizeDelta.x)-(CanvasRect.sizeDelta.x*0.5)),
((ViewportPosition.y*CanvasRect.sizeDelta.y)-(CanvasRect.sizeDelta.y*0.5)));
// now you can set the position of the ui element
rectTransform.anchoredPosition = WorldObject_ScreenPosition;
Your answer
Follow this Question
Related Questions
Converting Rect transform to World Position of 2D game 1 Answer
How to get UI RectTransform bottom Y position? 1 Answer
How to find the bottom position of a Image based on it's height? 2 Answers
Assign RectTransform to Array based on another Array 0 Answers
Render Player infront of UI while maintaining world space 0 Answers