Problem with OnMouseDrag!

Hi all… im trying to drag a gameobject around when i click and hold… this is the code im using:

publicclassscrollThroughScript : MonoBehaviour {

floatposition;
Vector3gameobjectPos;

voidOnMouseDrag ()
{
Vector3mousePos = newVector3(Input.mousePosition.x, Input.mousePosition.y, 0);
Vector3objPos = Camera.main.ScreenToWorldPoint(mousePos);

transform.position = objPos;
}
}

this is working alright… but im having this problem:

when i click… it brings the origin of the object straight to the mouse… i want to be able to just drag the object around the scene… all help would be lovely! :smile:
-Ross

You’ll have to calculate an offset on the first frame of the drag by subtracting the result of ScreenToWorldPoint from the object’s original position. Once you have the offset, you then subtract that offset from the ScreenToWorldPoint before you assign it back to the object’s position.

:smile:

oh thanks lolol

Use OnMouseDown to store the start position of the cursor:

private Transform Trans;
    private Vector3 ClickPosition;
    private Vector3 OriginalPosition;

    void Start()
    {
        Trans = transform;
    }

    void OnMouseDown()
    {
        Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
        ClickPosition = Camera.main.ScreenToWorldPoint(mousePos);
        OriginalPosition = Trans.position;
    }

    void OnMouseDrag()
    {
        Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
        Vector3 objPos = Camera.main.ScreenToWorldPoint(mousePos);
        Vector3 added = ClickPosition - objPos;
        Trans.position = OriginalPosition - added;
    }