Problem moving a GameObject with an OnDrag event when the canvas is in world space

I am trying to use the OnDrag event to change a gameobjects position.
I’ve done it before and it worked fine, but this time I can’t get it to be accurate.
The only difference between this project and the others is that this time the canvas is on world space coordinates.

I hava tried this code:

public void OnDrag(PointerEventData eventData)
{
    transform.localPosition = eventData.position;  
}

and this one:

public void OnDrag(PointerEventData eventData)
{
    transform.localPosition = Camera.main.WorldToScreenPoint(eventData.position);
}

and this one:

public void OnDrag(PointerEventData eventData)
{
    transform.localPosition = eventData.pointerPressRaycast.worldPosition;
}

and I even tried working with the delta, which gave me the best outcome, but it is still not very good:

public void OnDrag(PointerEventData eventData)
{
    Vector3 t = new Vector3(eventData.delta.x, eventData.delta.y, 0f);

    transform.localPosition += t;        
}

I also tried using the transform.position instead of localPosition, and allot of other combinations, Including stuff that I have never tried before like WorldToViewPort, even though I knew it was a Hail Mary.

I would really appreciate help with this, because the movement is very bad right now, and as far as I know the only thing that has changed from other projects is the world space canvas.

Try This:

Vector2 pos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(myCanvas.transform as RectTransform, Input.mousePosition, myCanvas.worldCamera, out pos);
transform.position = myCanvas.transform.TransformPoint(pos);

I’m not sure I’ve fully understood the question and this is quite old but I think this could be of use to someone so I’ll post it anyway.

If you’re working in world space then you need to be dealing with things in the world space.

Input.mousePosition returns a position on screen. The current project I’m working on is top-down so it’s fairly simple case of using a ray to convert the screen position to a location in the world:

    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    myObject.transform.position = new Vector3(ray.origin.x, 0, ray.origin.z);

An additional conditional check can be used by raycasting to be sure you’re on the ground. (If your game is not top down you can use this raycast to find the position in world space (of the ground)):

if (Physics.Raycast(ray, out hit))