Joe Blow Joe Blow - 3 months ago 20
C# Question

Unity3D UI, calculation for position dragging an item?

These days it's incredibly easy to drag UI elements in Unity: Make a few UI items. Add Component -> Event -> Event Trigger. Drop on the script below. Click to add the four obvious triggers. You're done.

However.

I'm totally lost in the relationship between pointer coordinates and UI coordinates (as seen in RectTransform and so on).

In

DragIt
below: how the hell do you move a UI panel correctly under the finger?

Say you have one large panel, with ten UIButton sitting in the panel with
Dragster
on the buttons. What is the relationship between the RectTransform coords and the mouse pointer ...

in short how do you move one of the button around at DragIt() below?

/* modern Unity drag of UI element */
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class Dragster:MonoBehaviour
{
public int index; // number each of your UI items
static bool beingDragged = false;
static int dragFrom;
public void DragStart()
{
beingDragged = true; dragFrom = index;
}
public void DragIt()
{
? ? W T F ? ?
}
public void DragEnd()
{
beingDragged = false;
}
public void DroppedBra()
{
Debig.Log("Drag: from/to " +dragFrom +" --> " +index);
}
}

Answer

An important announcement from JoeBlow...

Note - This does work absolutely perfectly.

Although this answer does not answer as such the question "converting the pointer data to UI coordinates", it is a huge contribution to Unity engineering and mankind generally. Thank you.


For Draging stuff I just do this :

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class Draggable : MonoBehaviour,
          IBeginDragHandler, IDragHandler, IEndDragHandler {

    public void OnBeginDrag(PointerEventData eventData) {}

    public void OnDrag(PointerEventData eventData) {
        //Debug.Log ("OnDrag");
        transform.position = eventData.position;
        }

    public void OnEndDrag(PointerEventData eventData) {}
}