- Home /
Converting Rect transform to World Position of 2D game
I have a game object which is a UI button. And another 2D sprite as another game object. In my 2D game, the player needs to drag the UI button to the top of the 2D sprite game object. and place it on top of it. I need to know how to calculate the world position of the UI button? I have used the following code but its not working.
//Calculating the position of UI button on drag end
private RectTransform recttransform=(RectTransform) transform.GetComponent(); private Vector3 endpos=recttransform.anchoredPosition; Vector3 trans=Camera.main.ScreenToWorldPoint(endpos);
//Calculating the position of stationary 2D sprite game object having sprite renderer component attached to it
Bounds b1=ChildDress.gameObject.GetComponent().bounds; Debug.Log ("B1"+b1); if(b1.Contains(trans)) { Debug.Log ("Success"); } else Debug.Log("False");
I have used two cameras in my project, one is for showing gui and the other is the main camera for the game. Can someone please help me in this problem? Thanks in advance.
Answer by median · Jan 28, 2016 at 09:45 AM
Hi, I think you can just use RectTransform.transform.position to convert that.
recttransform.position should actually do, RectTransform extrends Transform and the original values are still the same, so no converting is needed. In this case I believe position is the world position of the blue circle in the scene view representing your object's pivot point.
Is there any way to do this but in the other direction? So I have a world position and convert it to a RectTransform position?
Your answer
Follow this Question
Related Questions
Rect Transform to World Position Conversion 2 Answers
Worldspace canvas blocking input of Screen Space Overlay Canvas 0 Answers
Clickable Worldspace UI Buttons? 1 Answer
Aligning UI Elements in Code 0 Answers