- Home /
Set Position UI By Mouse Position
Hi,
I need to put a UI image following the mouse. 'the UI image center stay in the point of the mouse.' I used (Input.mousePosition) but it is not exactly the mouse pointer. anyone have any ideas for it?
Input.mousePosition is the mouse pointer, maybe your code is needing a conversion to a different coordinate system; show your code
Answer by curiouspers · Jan 25, 2015 at 02:59 PM
I think that one should help.
take a look at DragPanel example and anchoredPosition and anchoredPosition3D, use it like this:
image.rectTransform.anchoredPosition3D = new Vector3(my_new_x, my_new_y, my_new_z);
is not exactly the mouse pointer:
GetComponent(RectTransform).anchoredPosition3D = Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
sorry, maybe this is too late, but perhaps you need to use Camera.ScreenToWorldPoint OR Camera.ScreenPointToRay and Physics.Raycast in conjunction with anchoredPosition3D, documentation has good example
Answer by cdr9042 · Nov 05, 2020 at 03:40 AM
RectTransformUtility.ScreenPointToLocalPointInRectangle can help you
ScreenPointToLocalPointInRectangle(RectTransform rect, Vector2 screenPoint, Camera cam, out Vector2 localPoint);
rect: the parent RectTransform of the UI object you're moving.
screenPoint: your mouse position in screen space
Camera: the camera your Canvas is rendered on
localPoint: set the anchored position of the UI object to this vector
Example:
RectTransform movingUI;
RectTransform parentRect = movingUI.parent as RectTransform;
ScreenPointToLocalPointInRectangle(parentRect, mousePosition, Camera.main, out Vector2 localPoint);
movingUI.anchoredPosition = localPoint;
Your answer
Follow this Question
Related Questions
Change size of the new UI rect transform using scripts 0 Answers
Convert Input.mousePosition to RectTransform pivot position 2 Answers
How to change the Top and Bottom (rect.yMin and yMax) properties of a rectTransform, in a script? 2 Answers
[Unity 4.6 Beta] Rect Transform Position (New UI System) 7 Answers
Questions about UGUI Rect Transform Anchors. How to make UI objects scale, correctly, with screen? 1 Answer