2
\$\begingroup\$

This has been discussed a couple of times, but I didn't find any solution:

I want to set the position of an UI.Button to my mouse position. I can get the mouse position like this:

Vector3 cameraVector = Camera.main.ScreenToWorldPoint(Input.mousePosition);

Problem: The UI elements are using another "coordination system". How can I handle that problem?

\$\endgroup\$
3
\$\begingroup\$

Input.mousePosition is already in screen coordinates. You do not need any transfomations, just pass it to RectTransform.anchoredPosition.

Here is example of doing it: http://answers.unity3d.com/questions/781643/unity-46-beta-rect-transform-position-new-ui-syste.html

\$\endgroup\$
2
  • \$\begingroup\$ This is not working as expected. The mouse position is different to the position where the button is placed at. Do I need to take any changes at the Canvas? \$\endgroup\$
    – mosquito87
    Oct 20 '15 at 15:14
  • \$\begingroup\$ I believe you need to adjust button's Rect Transform anchors, pivot and positions or, at least, keep this parameters in mind when moving a button. Also be sure your canvas mode set to Screen space - Camera, or you will have new parameters to be taken into account. \$\endgroup\$
    – Skyblade
    Oct 20 '15 at 15:27
2
\$\begingroup\$

You probably want to use Unity's RectTransformUtility with a call to the ScreenPointToLocalPointInRectangle. Or ScreenPointToWorldPointInRectangle if you have a World Space UI. Then set the UI anchoredPosition.

\$\endgroup\$

You must log in to answer this question.

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