Mouse Drag and Drop C#

Hi everyone!

I’m currently learning the ropes of Unity 3D and I got stuck on a scripting problem.

What I’m trying to do is moving an object by holding down the left mouse button and then “placing” it by letting go.
I got it to kind of work with something as simple as the code below:

public float positionZ = 19.62604f;

void OnMouseDrag()
{
        transform.position = new Vector3(Input.mousePosition.x, Input.mousePosition.y +, positionZ);
}

The problem is that my object isn’t ending up by the mouse cursor, but instead it has a very large offset to it.
I understand that the mousePosition is in pixels, but I was just wondering if maybe someone could point me in the right direction of how to solve a problem like this.

Thank you beforehand!

Hi,
you have to convert your screen mouse position into world coordinate :wink:
Using: This

Alright, I’ll check it out. Thanks a lot!

So I tried to implement your suggestion cayou66, but I must be getting something wrong. This is what I’ve got:

public Vector3 p;

void OnMouseDrag()
{
       p = camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,
Input.mousePosition.y, Input.mousePosition.z));
       transform.position = p;
}

Now, the variable p seems to be set to the coordinates of my object in the Inspector when I try to drag it.
But this only updates once and there is no transformation of the position over time when I move the mouse.

I must be missing something here. Shouldn’t the “transform.position = p” be moving the object when I click and drag the mouse? Or maybe I somehow need to involve the Update function?

Regards!