- Home /
How to get mouse location on world canvas? [Unity 4.6]
I'm trying to build an inventory menu system using a canvas in world space. I'm trying to add drag-and-drop functionality, which requires me to know where the mouse is on the canvas so I know where to draw the item icon.
Does anybody know how to get that value?
Answer by JPOnion · Sep 06, 2014 at 01:10 AM
I found the answer. There's an great set of examples on the new GUI at:
http://forum.unity3d.com/threads/ui-example-project.263418/
One of the examples is on how to setup a drag-and-drop system. The canvas in the example isn't in world space, but it does work in world space.
Specific to my project, I did the following:
In the class that was going to be dragged, I added:
using UnityEngine.EventSystems;
and inherited the following interfaces:
IBeginDragHandler, IDragHandler, IEndDragHandler
Each interface only has one function:
OnBeginDrag: I created an icon and set its parent to the Canvas.
OnEndDrag: I destroy the icon.
OnDrag: I call this function (this came from one of the examples linked to earlier):
<pre><code>private void SetDraggedPosition(PointerEventData data)
{
if (dragOnSurfaces && data.pointerEnter != null && data.pointerEnter.transform as RectTransform != null)
m_DraggingPlane = data.pointerEnter.transform as RectTransform;
var rt = m_DraggingIcon.GetComponent{RectTransform}();
Vector3 globalMousePos;
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(m_DraggingPlane, data.position, data.pressEventCamera, out globalMousePos))
{
rt.position = globalMousePos;
rt.rotation = m_DraggingPlane.rotation;
}
}
EDIT: I can't seem to get the code formatting correct, so replace { and } with the correct brackets...
In the class that will receive the dragged item, I inherited the interface:
IDropHandler
This interface also only has one function:
OnDrop: The variable data.pointerDrag contains the GameObject that was being dragged. You can deal with the dropping logic how you want.
The SetDraggedPosition function from the example was what I was specifically looking for, but I hope the rest of the information is helpful, too.
Thanks, answer saved me from quite a bit of grief working with world space canvas for first time.
good, it's really good code and save my lost of time thanks
Your answer
