Reputation: 111
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
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