0

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!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, but could you explain why GameObject will move close to the camera? In fact I'm not very sure about what Z axis actually affects in 2D mode...
I updated my post, Z axis still matters in 2D mode however 2D objects behave as if there's no Z axis and with an orthographic camera they look as if so. but if you move an object to camera (or behind it) you won't see it.
So the "orthographic" camera can only show the objects whose Z axis value is greater than the camera? In other words, the camera is shooting from bottom to top?
yes exactly. also you must consider Clipping Planes of the camera
Now I understood. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.