- Home /
Apply Input.mousePosition to canvas
I did implement my very own context menu. If I right click somewhere, it should pop up right next to the cursor. (With a arbitrary but fixed offset) Just to be sure I didn't miss anything, I also present you the gameObjects as well.
Since "ItemInteractionContainer" coveres the whole screen, "ItemInteractionOptionContainer" is smaller (200x100px). Thus, I would like to reposition "ItemInteractionOptionContainer" whereever I do a right click. My code does following:
ContextMenuGameObject = "ItemInteractionContainer"
ContextMenuItemContainerGameObject = "ItemInteractionOptionContainer"
CanvasScaler scaler = ContextMenuGameObject.GetComponent<CanvasScaler>();
ContextMenuItemContainerGameObject.GetComponent<RectTransform>().anchoredPosition
= new Vector2(UnityEngine.Input.mousePosition.x
* scaler.referenceResolution.x / Screen.width, UnityEngine.Input.mousePosition.y * scaler.referenceResolution.y / Screen.height);
I did browse the web and found some "solutions". https://answers.unity.com/questions/849117/46-ui-image-follow-mouse-position.html https://stackoverflow.com/questions/37244471/click-and-drag-a-gameobject-in-a-overlay-canvas-in-unity
But neither does work. Either the panel (ItemInteractionOptionContainer) isn't even on the main Panel ("ItemInteractionContainer") or the Panel is slightly off the mouse. (Also the more I am at the screen edge, the more it drifts off)
This approach I came up with
ContextMenuItemContainerGameObject.GetComponent<RectTransform>().position = UnityEngine.Input.mousePosition;
Does work somehow. It is still off the cursor, but would be more or less ok for me. But as soon as I build the game and run it, the Container is again off-screen.
What would be the best way to set the position of a canvas to the mouse position?
Thanks in advance.
PS:
RectTransformUtility.ScreenPointToLocalPointInRectangle
on my canvas (ItemInteractionContainer) always returns (0,0)
Answer by Toemsel92 · May 08, 2018 at 10:15 PM
Could solve the problem. I somehow had 2 canvas in the scene. It works like a charm with just one canvas gameObject.
Answer by FlaSh-G · May 08, 2018 at 12:25 AM
I recently wrote this little class, feel free to use it.
https://gist.github.com/FlaShG/ac3afac0ef65d98411401f2b4d8a43a5