user3765498
user3765498

Reputation: 111

Converting from Pixel Coordinates to UI Coordinates in Unity

Does anyone know how to convert from Pixel Coordinates to UI Coordinates and vice-versa in Unity? Let's say for example I want to click somewhere on the screen with the mouse, and a UI Image to be at that click position. If I do this won't work:

Image img = null // I assign it via the inspector
void Update()
{
    if(Input.GetMouseButtonDown(0))
    {
        img.rectTransform.anchorPosition = Input.mousePosition;
    }
}

Upvotes: 2

Views: 4105

Answers (1)

maraaaaaaaa
maraaaaaaaa

Reputation: 8163

Image img = null // I assign it via the inspector
void Update()
{

        if(Input.GetMouseButtonDown(0))
    {
        Vector2 point;
        RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform)img.rectTransform.parent, Input.mousePosition, canvasCamera, out point);
        img.rectTransform.anchorPosition = point;
    }
}

Upvotes: 2

Related Questions