0
\$\begingroup\$

It seems raycast hit does not work for UI... is it possible to get the .textureCoord of a point hit by the mouse on a UI raw image? (raw image provided by a render camera elsewhere far far away)

\$\endgroup\$
1
\$\begingroup\$

The RectTransformUtility has a helper method for finding the position of a screen point inside anyRectTransform's bounding rectangle:

var rt = (RectTransform)rawImage.transform;

bool inside = RectTransformUtility.ScreenPointToLocalPointInRectangle(
    (RectTransform)rawImage.trasnform,
    Input.mousePosition,
    camera,
    out Vector2 pointInRect
);

Then you can just remap these coordinates from the local rectangle of the RawImage object into the UV space of the texture it's displaying:

if (inside) {
    Vector2 textureCoord = pointInRect - rt.rect.min;
    textureCoord.x *= rawImage.uvRect.width / rt.rect.width;
    textureCoord.y *= rawImage.uvRect.height / rt.rect.height;
    textureCoord += rawImage.uvRect.min;
}

Note that if your UI is in "Screen Space - Overlay mode", then the camera argument should be null.

If your texture coordinates are upside-down, you may need to set

trextureCoord.y = rt.rect.height - textureCoord.y;

before the scaling step.

\$\endgroup\$
1
  • \$\begingroup\$ Okay, this surely beats my GraphicCaster attempt - thank you!!! \$\endgroup\$
    – ina
    Jan 10 at 2:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .