Search Unity

Problem with dragging

Discussion in 'UGUI & TextMesh Pro' started by Mr_Benn, Jun 19, 2019.

  1. Mr_Benn

    Mr_Benn

    Joined:
    Feb 14, 2019
    Posts:
    25
    Hi

    I have created a UI canvas with some UI child elements on it. The dimensions of the canvas are 1600 x 800, with 0 in the centre.

    I have been trying to learn how to use the IDragHandler interface to drag some UI elements around on the canvas. However, I have a problem that I don't understand. The x y recttransform values of the UI Image to be dragged might start out at -500, -200, for example, but as soon as I try to drag the element, its x y values in the rect transfrom sky rocket to five figures and it disappears off canvas somewhere.

    All I'm doing on the dragged object is this:

    Code (CSharp):
    1. public class ItemDragHandler : MonoBehaviour, IDragHandler
    2. {
    3.     public void OnDrag(PointerEventData eventData)
    4.     {
    5.         transform.position = Input.mousePosition;
    6.     }
    7. }
    What am I not doing right?

    Cheers
     
    Last edited: Jun 24, 2019
  2. cecarlsen

    cecarlsen

    Joined:
    Jun 30, 2006
    Posts:
    862
  3. Mr_Benn

    Mr_Benn

    Joined:
    Feb 14, 2019
    Posts:
    25
  4. cecarlsen

    cecarlsen

    Joined:
    Jun 30, 2006
    Posts:
    862
    I'm diving into IUElements at the moment and can't remember all details on Canvas positioning. Perhaps try to manipulate the rectTransform (GetComonent<RectTransform>) instead of the transform and also use the position values stored in your PointerEventData. I remember that you can set an absolute position by setting both anchorMin and anchorMax on rectTransform to the the same position.
    https://docs.unity3d.com/ScriptReference/EventSystems.PointerEventData.html
     
    Mr_Benn likes this.