DarkZero
DarkZero

Reputation: 2334

Why this code for 2D dragging in Unity doesn't work?

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

Answers (1)

Bizhan
Bizhan

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:

  1. GameObject moves close to camera (in Z axis) and you need to modify its Z manually (this is the reason behind the weird behaviour you experienced). This is because camera position in Z axis is always different than the visible objects it's rendering. say camera is at 0,0,-10 and GameObject is at 0,0,0 in this case Camera.main.ScreenToWorldPoint(Input.mousePosition) will always return -10 in Z axis
  2. Always the center of GameObject sticks to the mouse, not the point where you start drag.

Note:

You can now change both Z values from 10 to 0. That's because offset is being applied in every frame.

Upvotes: 1

Related Questions