Reputation: 2334
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!
Upvotes: 0
Views: 843
Reputation: 17115
When you drag a GameObject you need to move it by its delta in OnMouseDrag. By delta I mean the difference between the positions within the previous frame and current frame.
But the current position is unknown before the drag starts, this is why offset should be set just before you start to drag i.e. in OnMouseDown.
If you don't set offset in OnMouseDown then two things happen:
0,0,-10
and GameObject is at 0,0,0
in this case Camera.main.ScreenToWorldPoint(Input.mousePosition)
will always return -10 in Z axisYou can now change both Z values from 10 to 0. That's because offset is being applied in every frame.
Upvotes: 1