1

I've attached the following script to an Image inside the Canvas :

public class DragMe : MonoBehaviour, IDragHandler
{
    public void OnDrag(PointerEventData eventData)
    {
        this.transform.localPosition += (Vector3)eventData.delta;
    }
}

The problem is, as I drag further, the Image goes away more and more from under the pointer. When I drag back to the start position the Image comes back where it was under the finger/pointer.

changing the code to:

this.transform.position = eventData.position;

causes the object to jump away somewhere else.

Any help is much appreciated.

Update: Guys, if you read my code and the supposed duplicate question you see their answer is my question! But it has an issue, i.e. the object doesn't stay under the dragging finger/pointer and keeps going away further as you keep dragging!

Update 2: Image:

enter image description here

Canvas:

enter image description here

Camera:

enter image description here

Blendester
  • 1,583
  • 4
  • 19
  • 43

1 Answers1

3

It's better to use Screen Space - Overlay if the camera's viewport is unchanged. Then following code will work:

this.transform.position = eventData.position;

To use Screen Space - Camera, you need transform the event position into the camera space:

Vector3 position = eventData.position;
var canvas = image.canvas;
position.z = canvas.planeDistance;
image.transform.position = canvas.worldCamera.ScreenToWorldPoint(position);
shingo
  • 18,436
  • 5
  • 23
  • 42