I'm new to Unity, and I tried to implement mouse dragging today. I wrote the following code:
void OnMouseDrag() { Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10); Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint); transform.position = curPosition; } However, upon dragging the GameObject it disappeared from the camera, but I can see it moved from its original place in the Scene View.
I searched in the Internet, finding that the correct version is like this:
void OnMouseDown() { offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10)); } void OnMouseDrag() { Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10); Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset; transform.position = curPosition; } I cannot figure out why the offset value is necessary. Why it makes difference? Could anyone give me an explanation?
Thank you!