[Unity]Converting from screen coordinates to world coordinates isn’t working properly.

この記事は約4分で読めます。
スポンサーリンク

Things I want to do

This article provides solutions for when converting from screen coordinates (Input.mousePosition) to world coordinates doesn’t work properly.

premise

The Canvas Render mode is Screen Space – Overlay

The obtained world coordinates are used to specify the location in the UI.

Examples of what didn’t work

I tried the following code after looking it up online, but it didn’t work.

(The process didn’t fail; rather, the desired value couldn’t be obtained.)

Camera.main.ScreenToWorldPoint(Input.mousePosition);
スポンサーリンク

countermeasure?

From the way it works, it seems that when using Screen Space – Overlay with World coordinates, World coordinates = Screen coordinates.

However, I read through the official documents and other materials, but I couldn’t find any section that explicitly states this.

スポンサーリンク

countermeasure

If World coordinates equal Screen coordinates, there’s no need for conversion, but since there’s no proof, I’ve taken precautions in the code for safety.

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));

Here, the `tf` used in the second line (first argument) and the `tf` used in the third line must be the same Transform class object.

Additionally, items that meet the following conditions are required.

  • It has a RectTransform component.
  • It is a UI

Conversely, it’s perfectly fine if it’s inactive.

Furthermore, the click point can be outside the target GameObject.

In other words, it can be a single-pixel inactive UI or a Canvas.

スポンサーリンク

Result

The Canvas Render mode is Screen Space – Overlay

コメント

タイトルとURLをコピーしました