Drag object by point clicked vs transform center

Hi, I’m moving an object via click/drag, but it instantly moves the objects transform center point to the hit.point position.
What I’d like it to do is move the object relative to the point I actually clicked on it. ex: If I click on the corner, let the mouse continue moving from the corner of the object, not suddenly snap to the center of the object. Any idea what I’m doing wrong?

      ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         if(Physics.Raycast(ray, hit) && hit.transform == this.transform)
         {
             this.transform.position.x = hit.point.x;
             this.transform.position.z = hit.point.z;
         }

That’s quite simple. All you have to do is store the offset from the objects center to the initial hitpoint when you start dragging. When you set the object to it’s new position you simply revert the offset.

However your code has another problem. You get the new position by raycasting onto the object itself. Depending on the objects shape that might have strange results. Another way is to store the distance of the initial hit as well and simply place the object at this distance from the camera. If you use an orthographic camera the depth of course doesn’t matter as long as the camera is aligned with the world z-axis.

I guess you use UnityScript? (guess based on your “hit” variable)

// UnityScript
private var dragging = false;
private var dragOffset : Vector3;
private var dragDistance : float;

function Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        var hit : RaycastHit;
        if(Physics.Raycast(ray, hit) && hit.transform == transform)
        {
            dragging = true;
            dragDistance = hit.distance;
            dragOffset = transform.position - hit.point;
        }
    }
    if (Input.GetMouseButton(0) && dragging)
    {
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        transform.position = ray.GetPoint(dragDistance) + dragOffset;
    }
    else
    {
        dragging = false;
    }
}

Here’s a stripped down C# version if you are just dealing with mouse and 2D

	Vector3 mousepos;
	Vector3 clickedPos;
	Vector3 offSet;
   
	void OnMouseDown() {
		clickedPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
		offSet = transform.position - clickedPos;

	}

	void OnMouseDrag() {
		mousepos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
		transform.position = new Vector3(Mathf.Round(mousepos.x), Mathf.Round(mousepos.y), 0) + offSet;
	}