Convert Pointer coordinates to RectTransform coordinates

Hi,

Is there a simpler way of getting the position of a mouse/pointer click in RectTransform?

Use case is clicking on a map; I currently have a kludgy/brittle way of getting it done, but I feel there should be a more straightforward way of getting this done. Something similar to the Screen/View/World functions available in the Camera class?

1 Like
RectTransformUtility.ScreenPointToLocalPointInRectangle (RectTransform rect, Vector2 screenPoint, Camera cam, out Vector2 localPoint)
1 Like

Hi Tim,

We’re already using that, however it currently feels a little odd because it gives us a point from the center of the recttransform, but we can’t seem to get the width and height of the RectTransform. Instead, we’re getting the width and height from the the RawImage using the RectTransform.

Is there a way to get the Width and Height of the RectTransform as displayed in the Inspector?

Sorry for the basic questions, we’re just coming to grips with the coordinate spaces used in the new UI.

Thanks!

That is expected when the pivot is in the center. That is exactly what the point in local space means, since the origin of the RectTransform is its pivot.

If you get the rect of the RectTransform using rectTransform.rect, it will similarly be expressed in this local space.

The final calculated width of a RectTransform (in its local space) is rectTranasform.rect.width / rectTransform.rect.height

Thanks Tim and Rune!

I had additionally conflated Anchors and Pivot points causing my confusion; once I got that sorted out (and actually read the help text in the anchor window) it was pretty straightforward.

Thanks guys!

1 Like

For those who stumble across this looking for answers much later, as I did, here’s an important point that isn’t documented anywhere:

If you are using a canvas in ‘Screen Space - Overlay’ (e.g. a 2D canvas), you have to pass null as the argument for the camera to the RectTransformUtility. If you try to pass the main camera, or any other camera in the scene, in as an argument, you will get bizarre results that seem to have no bearing on reality.

Here’s the Answers post I finally ran across that clued me in to this issue: How to get screen position of a RectTransform when canvas render mode set to "Screen Space - Overlay" - Questions & Answers - Unity Discussions

5 Likes

I did a coordinate translation tool for the UI to convert from / to: Screen Space (pixels), anchor coordiantes, rect coordinates, canvas coordinates, coordinates of objects located at different containers, etc. Take a look: [RELEASED] EASIER UI - Community Showcases - Unity Discussions