The purpose
This article provides solutions for when converting from screen coordinates (Input.mousePosition) to world coordinates doesn’t work as expected.
Premise
Canvas’s Render Mode is Screen Space – Overlay.
The obtained World Coordinates are used for specifying the UI’s position.
A failed example
I tried the following code after looking it up online, but it didn’t work as expected. (It didn’t fail to process, but I couldn’t get the desired value.)
Camera.main.ScreenToWorldPoint(Input.mousePosition);
Solution?
It seems that when using World coordinates with Screen Space – Overlay based on its behavior, World coordinates are equivalent to Screen coordinates. However, I couldn’t find any explicit mention of this in the official documentation.
Solution
If world coordinates and screen coordinates were the same, no conversion would be required. However, lacking definitive proof, I’ve implemented safeguards in the code just in case.
The following code worked.
Vector2 localPoint;
RectTransformUtility.ScreenPointToLocalPointInRectangle(trans.GetComponent<RectTransform>(), Input.mousePosition, null, out localPoint);
Vector3 v = tf.TransformPoint(new Vector3(localPoint.x, localPoint.y, 0));
The tf
used in the second line as the first argument, and the tf
used in the third line, must be the same Transform
class instance.
We also require an item that satisfies the following criteria.
- Having a RectTransform component.
- Being a UI element.
On the contrary, having it inactive is not a problem either.
Additionally, the click point can be outside the target GameObject without issue.
This means that even a 1-pixel inactive UI element or Canvas would be acceptable.
Result
The world coordinates when the render mode is Screen Space – Overlay have been successfully acquired.
comment